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;
}
};