binary-tree-level-order-traversal-ii

class Solution {
public:
    vector<vector<int> > levelOrderBottom(TreeNode *root) {
        vector<vector<int>>ans;
        if(!root)return ans;
        queue<TreeNode*>cur,nex;
        cur.push(root);
        while(!cur.empty())
        {
            vector<int>level;
            while(!cur.empty())
            {
                TreeNode*top=cur.front();
                cur.pop();
                level.push_back(top->val);
                if(top->left)nex.push(top->left);
                if(top->right)nex.push(top->right);
            }
            swap(cur,nex);
            ans.push_back(level);
        }
        reverse(ans.begin(),ans.end());
        return ans;
    }
};


class Solution {
public:
    vector<vector<int> > levelOrderBottom(TreeNode *root) {
        vector<vector<int>>ans;
        if(!root)return ans;
        queue<TreeNode*>q;
        q.push(root);
        while(!q.empty())
        {
            int size=q.size();
            vector<int>temp;
            while(size--)
            {
                TreeNode*top=q.front();
                q.pop();
                temp.push_back(top->val);
                if(top->left)q.push(top->left);
                if(top->right)q.push(top->right);
            }
            ans.push_back(temp);
        }
        reverse(ans.begin(),ans.end());
        return ans;
    }
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容