Leetcode 107 - Binary tree level order traversal II

Note:

  • Very similar to Leetcode 102, but we just need to reverse the result.

Given the root of a binary tree, return the bottom-up level order traversal of its nodes’ values. (i.e., from left to right, level by level from leaf to root).

Example

img

1
2
Input: root = [3,9,20,null,null,15,7]
Output: [[15,7],[9,20],[3]]
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
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrderBottom = function(root) {
let queue = [root];
let result = [];
if (!root) return result;
while (queue.length) {
let curLevel = [];
let length = queue.length;
for (let i = 0; i < length; i++) {
let node = queue.shift();
curLevel.push(node.val);
node.left && queue.push(node.left);
node.right && queue.push(node.right);
}
result.push(curLevel);
}
return result.reverse();
};