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;
    }
}

 

posted @ 2021-04-06 16:50  小怀Vivian  阅读(829)  评论(0编辑  收藏  举报