算法之树
树的遍历
tip
- 前序遍历:先根节点,再左节点,最后右节点
- 中序遍历:先左节点,再根节点,最后右节点
- 后序遍历:先左节点,再右节点,最后根节点
二叉树的中序遍历
递归最简单:
/**
* 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 inorder(root) {
if(root == null) {
return;
}
inorder(root.left);
ans.push(root.val);
inorder(root.right);
})(root)
return ans;
};
迭代:
var inorderTraversal = function(root) {
const ans = [];
// 栈
const stack = [];
while(root || stack.length) {
while(root) {
stack.push(root);
root = root.left;
}
root = stack.pop();
ans.push(root.val);
root = root.right;
}
return ans;
};