中序遍歷二叉樹(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);
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM