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