Egbert Lin's Blog

“Life is not a race, but a journey to be savoured each step of the way” by Brian Dyson

[LeetCode Road] Binary Tree Level Order Traversal II - Solution/C++

107. Binary Tree Level Order Traversal II

Question:

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

Example:

For example: Given binary tree [3,9,20,null,null,15,7],

   3
   / \
  9 20
   / \
   15  7

return its bottom-up level order traversal as:

[
  [15,7],
  [9,20],
  [3]
]

Source code

Version 1

Idea:
I made a big mistake, I always think the solution that find the deepest depth first, the go back to the root with each layers. I realized an efficient approach until I had refered to Huahua's Tech Road.

You must understand how to implement a two dimensional vector first. Write a function as recursion, store each elements from top of tree. res.size() <= depth is an important statement to expand 2D vector size. Then, we must go through every left & right nodes and store it based on correspondingly depth. Finaly, let go back to original function, we must use reverse() to pass the answers.

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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector <vector<int> > res;
levelOrderBottom(root, 0, res);
reverse(res.begin(), res.end());
return res;
}
private:
void levelOrderBottom(TreeNode* root, int depth, vector<vector<int>>& res){
if(!root) return;
while(res.size() <= depth) res.push_back({});
res[depth].push_back(root->val);
levelOrderBottom(root->left, depth + 1, res);
levelOrderBottom(root->right, depth + 1, res);
}
};