二叉树的层次遍历方式:非递归方式

首先创建一棵搜索二叉树,搜索二叉树的代码在我之前的博客已经贴出来了,这里我就不细讲了,感兴趣的小伙伴可以去翻翻之前的博客或者是网上搜索其他人写的搜索二叉树代码都是可以的,原理上差别不大应该:

let bst = new BST();

bst.insert(5);
bst.insert(3);
bst.insert(4);
bst.insert(7);
bst.insert(6);
bst.insert(9);
bst.insert(8);
bst.insert(10);
bst.insert(2);
bst.insert(0);
bst.insert(-1);
bst.insert(1);

对应的二叉树如下 

要想层次遍历(从上到下,从左到右输出节点),需要准备个队列(先进先出的)用来存放我走过的节点,首先是从根节点走走完根节点pop出去,此时队列的大小为0,这时候将左子节点和右子节点依次push进队列,同时将依次访问的节点放到一个数组里方便打印接地那的值,直到队列的大小为0,这时候所有的节点已经访问过了,这时候可以依次打印他们的值,具体代码如下:

let treeLayer = (root) => {
    let queue = [];
    let headQue = new Queue();

    queue.push(root);
    headQue.push(root);

    while(headQue.size() !== 0) {
        root = headQue.pop();
        if(root.left) {
            headQue.push(root.left);
            queue.push(root.left);
        }
        if(root.right) {
            headQue.push(root.right);
            queue.push(root.right);
        }

    }
    let res = "";
    for(let item of queue) {
        res += " " + item.data;
    }
    console.log("res is ",res);
    
}

这里用到了数据结构的队列:

function Queue() {
    this.data = [];
}

Queue.prototype.pop = function() {
    return this.data.shift();
}
Queue.prototype.push = function(item) {
    this.data.push(item);
}
Queue.prototype.size = function() {
    return this.data.length;
}

let que = new Queue();
que.push(3);
que.push(4);
que.push(5);
que.push(8);
que.push(9);

while(que.size() !== 0) {
    console.log(que.pop());
}
module.exports.queue = Queue;

最后调用 treeLayer(bst.root);

得到输出: 5 3 7 2 4 6 9 0 8 10 -1 1 正是我们想要的结果

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值