题目链接
Binary Tree Level Order Traversal II
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]
return its bottom-up level order traversal as:
解题思路
TODO (稍后补上)
解题代码
/**
* 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<TreeNode* >> output;
vector<vector<int>> values;
if (0 == root) {
return values;
}
TreeNode* broot = root;
vector<TreeNode* > tmp;
vector<int> vtmp;
tmp.push_back(broot);
vtmp.push_back(broot->val);
output.push_back(tmp);
values.push_back(vtmp);
int index = 0;
while(index < output.size()) {
vector<TreeNode* > cur;
vector<int> vcur;
for(int i=0;i<output[index].size();i++) {
if(output[index][i]->left != 0) {
cur.push_back(output[index][i]->left);
vcur.push_back(output[index][i]->left->val);
cout << output[index][i]->left->val<<" ";
}
if(output[index][i]->right != 0) {
cur.push_back(output[index][i]->right);
vcur.push_back(output[index][i]->right->val);
cout << output[index][i]->right->val << " ";
}
}
if(cur.size()!=0) {
output.push_back(cur);
values.push_back(vcur);
}
index++;
}
vector<vector<int>> re_values;
for(int k=values.size()-1;k>=0; --k) {
re_values.push_back(values[k]);
}
return re_values;
}
};