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).
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]
]
Runtime: 8 ms, faster than 100.00% of C++ online submissions for Binary Tree Level Order Traversal II.
Memory Usage: 15 MB, less than 13.70% of C++ online submissions for Binary Tree Level Order Traversal II.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> result;
// tips: regard level of depth as index.
traverse(root, result, 0);
// reverse
reverse(result.begin(), result.end());
return result;
}
void traverse(TreeNode* root, vector<vector<int>> &v, int level) {
if (root == NULL) {
return;
}
if (v.empty() || level > (v.size() - 1)) { // add a vector for current level if it doesn't exist.
v.push_back(vector<int>());
}
// push_back to the vector for current level;
v[level].push_back(root->val);
int nextLevel = level + 1;
traverse(root->left, v, nextLevel);
traverse(root->right, v, nextLevel);
}
};