add: 二叉树的层序遍历 II

This commit is contained in:
2020-05-13 13:59:30 +08:00
parent 7ff3a150b7
commit 8f84fc8c66
3 changed files with 48 additions and 1 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 && node.left) queue.push(node.left)
if (node && node.right) queue.push(node.right)
if (node) tmp.push(node.val)
}
if (tmp.length) res.unshift(tmp)
}
return res
}