二叉树(1):二叉树的前、中、后和层次遍历
二叉树入门级别。
1.二叉树前序遍历
题目144.二叉树的前序遍历
/*** Definition for a binary tree node.* function TreeNode(val, left, right) {* this.val = (val===undefined ? 0 : val)* this.left = (left===undefined ? null : left)* this.right = (right===undefined ? null : right)* }*/
/*** @param {TreeNode} root* @return {number[]}*/
var preorderTraversal = function (root) {let ans = [];function dfs(root) {if (root === null) {return;}ans.push(root.val);dfs(root.left);dfs(root.right);}dfs(root);return ans;
};
2.二叉树中序遍历
题目94.二叉树中序遍历
/*** Definition for a binary tree node.* function TreeNode(val, left, right) {* this.val = (val===undefined ? 0 : val)* this.left = (left===undefined ? null : left)* this.right = (right===undefined ? null : right)* }*/
/*** @param {TreeNode} root* @return {number[]}*/
var inorderTraversal = function (root) {const ans = [];function dfs(root) {if (!root) {return;}dfs(root.left);ans.push(root.val);dfs(root.right);}dfs(root);return ans;
};
3.二叉树后序遍历
题目145.二叉树的后序遍历
/*** Definition for a binary tree node.* function TreeNode(val, left, right) {* this.val = (val===undefined ? 0 : val)* this.left = (left===undefined ? null : left)* this.right = (right===undefined ? null : right)* }*/
/*** @param {TreeNode} root* @return {number[]}*/
var postorderTraversal = function (root) {const ans = [];function dfs(root) {if (!root) {return;}dfs(root.left);dfs(root.right);ans.push(root.val);}dfs(root);return ans;
};
4.二叉树层次遍历
题目102.二叉树的层序遍历
//方法一,双队列
/*** Definition for a binary tree node.* function TreeNode(val, left, right) {* this.val = (val===undefined ? 0 : val)* this.left = (left===undefined ? null : left)* this.right = (right===undefined ? null : right)* }*/
/*** @param {TreeNode} root* @return {number[][]}*/
var levelOrder = function (root) {const answers = [];let cur = [root];while (root && cur.length) {let next = [];let answer = [];for (node of cur) {if (node.left) {next.push(node.left);}if (node.right) {next.push(node.right);}answer.push(node.val);}answers.push(answer);cur = next;}return answers;
};//方法二:单个队列
/*** Definition for a binary tree node.* function TreeNode(val, left, right) {* this.val = (val===undefined ? 0 : val)* this.left = (left===undefined ? null : left)* this.right = (right===undefined ? null : right)* }*/
/*** @param {TreeNode} root* @return {number[][]}*/
var levelOrder = function (root) {const answers = [];let queue = [root];while (root && queue.length) {let answer = [];let n = queue.length;let count = 0;while (count !== n) {let node = queue[0];if (node.left) {queue.push(node.left);}if (node.right) {queue.push(node.right);}answer.push(node.val);queue.shift();count++;}answers.push(answer);}return answers;
};