中序遍历二叉树(js)

leetcode上刷到一题中序遍历一颗二叉树的题,两种方法,使用递归或者栈

原题及解答:https://leetcode.com/problems/binary-tree-inorder-traversal/discuss/164579/recursion-and-stack-solve-the-problem-by-js

中序遍历:按照左,根,右的顺序遍历二叉树

使用栈:先将根节点入栈,找到所有左节点入栈,直到没有左节点为止,然后出栈存入结果数组,每出一个,对比该根节点的右子节点是否有左节点,若有则入栈,否则继续出栈

代码如下

var inorderTraversal=function(root){
        var  res=[];
        //
        var s=[];
        var p = root;
    
        while (p || s.length>0) {
            //直至左节点为空,即没有左节点为止
            while (p) {
                s.push(p);
                p = p.left;
            }
            //出栈,存放根节点
            p = s.pop();
            res.push(p.val);
            p = p.right;
        }
        return res;
}

递归:

var inorderTraversal = function(root) {
    var res=[];
    inorder(root,res);
    return res;
};
//按照左 根 右顺序遍历
function inorder(root,res){
    if(!root) return ;
    inorder(root.left,res);
    res.push(root.val);
    inorder(root.right,res);
}
原文地址:https://www.cnblogs.com/xingguozhiming/p/9557597.html