方法一:普通宽度优先
class Solution {
public:
vector<vector<int> > levelOrderBottom(TreeNode *root) {
vector <vector<int> >ans;
if(root==NULL)
return ans;
queue <TreeNode*> q1;
queue <TreeNode*> q2;
bool flag=true;
q1.push(root);
while(!q1.empty()||!q2.empty()){
vector<int> tmp;
if(flag){
while(!q1.empty()){
TreeNode *node;
node=q1.front();
tmp.push_back(node->val);
if(node->left){
q2.push(node->left);
}
if(node->right){
q2.push(node->right);
}
q1.pop();
}
ans.push_back(tmp);
flag=false;
}
else{
while(!q2.empty()){
TreeNode *node;
node=q2.front();
tmp.push_back(node->val);
if(node->left){
q1.push(node->left);
}
if(node->right){
q1.push(node->right);
}
q2.pop();
}
ans.push_back(tmp);
flag=true;
}
}
vector<vector<int> > v;
for(int i=ans.size()-1; i>=0; i--)
v.push_back(ans[i]);
return v;
}
};
107 Binary Tree Level Order Traversal II
最新推荐文章于 2018-03-24 20:32:25 发布