107. Binary Tree Level Order Tra
2018-06-17 本文已影响0人
SilentDawn
Problem
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
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]
]
Code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
static int var=[](){
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
class Solution {
public:
vector<vector<int>> storage;
vector<vector<int>> levelOrderBottom(TreeNode* root) {
levelOrder(0,root);
reverse(storage.begin(),storage.end());
return storage;
}
void levelOrder(int level,TreeNode *node){
if(node!=NULL){
if(storage.size()<=level)
storage.push_back(vector<int>());
storage[level].push_back(node->val);
levelOrder(level+1,node->left);
levelOrder(level+1,node->right);
}
}
};
Result
![](https://img.haomeiwen.com/i140476/240200a9df776963.png)