My 3ms C++ BFS Solution


  • 0
    N
    class Solution {
    public:
        vector<vector<int>> levelOrderBottom(TreeNode* root) {
            vector<vector<int>> ans;
            if (root==NULL)
                return ans;
      
            queue<TreeNode*> queue0;
            vector<int> vec0;
            TreeNode *p=root;
            queue0.push(p);
            while (!queue0.empty())
            {
                int qsize=queue0.size();
                for (int i=0;i<qsize;i++)
                {
                    p=queue0.front();
                    if (p->left!=NULL)
                        queue0.push(p->left);
                    if (p->right!=NULL)
                        queue0.push(p->right);
                    vec0.push_back(p->val);
                    queue0.pop();
                }
                ans.push_back(vec0);
                vec0.clear();
            }
            reverse(ans.begin(), ans.end());
            return ans;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.