Leetcode题解之 —— 二叉树的层次遍历 II

思路


BFS算法

  • queue队列辅助
  • 内部循环分组
  • result反转

题解


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrderBottom = function (root) {
if (!root) {
return [];
}

const [result, queue] = [[], [root]];

while (queue.length) {
// 保存分组的值
const [group, queueLen] = [[], queue.length];
let count = 0;

while (count < queueLen) {
const currentNode = queue.shift();
group.push(currentNode.val);
currentNode.left && (queue.push(currentNode.left));
currentNode.right && (queue.push(currentNode.right));
count++;
}

result.push(group);
}

return result.reverse();
}