二叉树层次遍历(BFS)
框架
队列 unshift() push()
function levelTraverse(root) {
let que = [];
que.push(root);
while (que.length !== 0) {
let size = que.length;// 防止数组塌陷问题
// 同一层
for (let i =0 ; i < size; ++i) {
let cur = que.shift();
// do something with current node.....
// 加入左孩子
// 加入右孩子
}
}
}
实现二叉树的层次遍历
function TreeNode(val, left, right) {
this.val = (val === undefined ? 0 : val)
this.left = (left === undefined ? null : left)
this.right = (right === undefined ? null : right)
}
function levelTraversal(root) {
let que = [],
result = [];
que.push(root);
while (que.length !== 0) {
let level = [],
size = que.length;
// 一层中的节点
for (let i = 0; i < size; ++i) {
let cur = que.shift();
// 同一层中的一个节点
level.push(cur.val);
if (cur.left !== null) {
que.push(cur.left);
}
if (cur.right !== null) {
que.push(cur.right);
}
}
result.push(level);
}
return result;
}
测试
let root = {
val: 1,
left: {
val: 2,
left: {
val: 4,
left: null,
right: null
},
right: {
val: 5,
left: null,
right: null
}
},
right: {
val: 3,
left: {
val: 6,
left: null,
right: null
},
right: {
val: 7,
left: null,
right: null
}
}
}
let result = levelTraversal(root);
console.log(result);
// [ [ 1 ], [ 2, 3 ], [ 4, 5, 6, 7 ] ]
慢慢来,比较快!基础要牢,根基要稳!向大佬致敬!