107 Binary Tree Level Order Traversal II

方法一:普通宽度优先
class Solution {
public:
    vector > levelOrderBottom(TreeNode *root) {
        vector  >ans;
        if(root==NULL)
            return ans;
        queue  q1;
        queue  q2;
        bool flag=true;
        q1.push(root);
        while(!q1.empty()||!q2.empty()){
            vector 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 > v;
        for(int i=ans.size()-1; i>=0; i--)
            v.push_back(ans[i]);
        return v;
    }
};

你可能感兴趣的:(LeetCode)