二叉树的递归遍历
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 res = [];
const dfs = function(root) {
if (root === null) return;
// 先序遍历所以从父节点开始
res.push(root.val);
// 递归左子树
dfs(root.left);
// 递归右子树
dfs(root.right);
}
// 只使用一个参数 使用闭包进行存储结果
dfs(root);
return res;
};
前序遍历方法二:
/**
* 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) {
return root
? [
// 前序遍历:中左右
root.val,
// 递归左子树
...preorderTraversal(root.left),
// 递归右子树
...preorderTraversal(root.right),
]
: [];
};
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) {
let res = [];
const dfs = function(root) {
if (root === null) {
return;
}
dfs(root.left);
res.push(root.val);
dfs(root.right);
}
dfs(root);
return res;
};
中序遍历方法二:
/**
* 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) {
return root
? [
// 中序遍历:左中右
// 递归左子树
...inorderTraversal(root.left),
root.val,
// 递归右子树
...inorderTraversal(root.right),
]
: [];
};
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) {
let res = [];
const dfs = function(root) {
if (root === null) {
return;
}
dfs(root.left);
dfs(root.right);
res.push(root.val);
}
dfs(root);
return res;
};
后序遍历方法二:
/**
* 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) {
// 后序遍历:左右中
return root
? [
// 递归左子树
...postorderTraversal(root.left),
// 递归右子树
...postorderTraversal(root.right),
root.val,
]
: [];
};