js實現二叉樹的先序、中序、后序遍歷,采用遞歸和非遞歸方法


function TreeNode(x){
this.val=val;
this.left=null;
this.right=null;
}
// 遞歸方法
function threeOrders(root){
let preArray=[],middleArray=[],lastArray=[];
//先序遍歷:根、左、右
function preOrder(root){
if(root){
preArray.push(root.val);
preOrder(root.left);
preOrder(root.right);
}
}
//中序遍歷 : 左 根 右
function inOrder(root){
if(root){
inOrder(root.left)
middleArray.push(root.val);
inOrder(root.right);
}
}
//后序遍歷:左右根
function lastOrder(root){
if(root){
lastOrder(root.left);
lastOrder(root.right);
lastArray.push(root.val);
}
}
preOrder(root);
inOrder(root);
lastOrder(root);
return [preArray,middleArray,lastArray]
}
function threeOrders(root){
    //非遞歸算法實現先序遍歷二叉樹,根左右,所以向數組中push一個元素
    function preOrder(root){
        let res=[],
        stack=[root];
        while(stack.length>0){
            let node=stack.pop();
            res.push(node.val);
            if(node.right){
                stack.push(node.right);
            }
            if(node.left){
                stack.push(node.right);
            }

        }
        return res;
    }
    //非遞歸算法 實現中序遍歷二叉樹   首先遍歷找到最深層的左子樹,
    function inOrder(root){
        let res=[],
            stack=[];
            while(root||stack.length>0){
                while(root){
                    stack.push(root);
                    root=root.left;
                }
                root=stack.pop();
                res.push(root.val);
                root=root.right;
            }
            return res;
    }
    // 非遞歸算法實現后序遍歷二叉樹, 和先序遍歷二叉樹類似,唯一區別是向數組中unshift元素,先push左再push右
    function lastOrder(root){
        let res=[],
        stack=[root];
        while(stack.length>0){
            let node=stack.pop();
            res.unshift(node.val);
            if(node.left){
                stack.push(node.left);
            }
            if(node.right){
                stack.push(node.right);
            }
        }
        return res;
    }
}

 


免責聲明!

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



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