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,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
confused what "{1,#,2,3}"
means? > read
思路:与Binary Tree Level Order Traversal这题一致,就是将最后的结果倒置一下即可。
class Solution {
public:
vector<vector<int> > levelOrderBottom(TreeNode *root)
{
queue<TreeNode*> L;
TreeNode* temp;
vector<int>v;
vector<TreeNode*>vt;
vector<vector<int> >vv;
if(root)
{
v.push_back(root->val);
vv.push_back(v);
}
L.push(root);
while(!L.empty())
{
temp = L.front();
vt.push_back(temp);
L.pop();
if(!temp)
continue;
L.push(temp->left);
L.push(temp->right);
}
int i,j,cnt=0;
int step = 3;
for(i=1; i<vt.size(); i=j)
{
v.clear();
for(j=i; j<step && j<vt.size(); j++)
{
if(vt[j]!=NULL)
{
v.push_back(vt[j]->val);
cnt+=2;
}
}
step = j+cnt;
cnt = 0;
if(j<vt.size())
vv.push_back(v);
}
reverse(vv.begin(), vv.end());//结果倒置
return vv;
}
};