add: 二叉树的层序遍历

This commit is contained in:
2020-05-13 13:55:12 +08:00
parent 36b0434402
commit f1564fe56d
3 changed files with 44 additions and 0 deletions

View File

@ -0,0 +1,28 @@
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
export const levelOrder = function (root) {
const res = []
const queue = [root]
while (queue.length) { // BFS
const tmp = []
const leave = queue.length // 记录这一层有几个
for (let i = 0; i < leave; i++) { // 一次性把固定个数的队列执行完
const node = queue.shift()
if (node.left) queue.push(node.left)
if (node.right) queue.push(node.right)
tmp.push(node.val)
}
res.push(tmp)
}
return res
}