js实现二叉树的先序,中序,后序遍历,采用递归和非递归两种方法。

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.left);
            }

        }
        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;
    }
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哆啦咪唏

看到这里了,不留下点什么吗

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值