Share: C++ solution 8ms, easy to understand


  • 1
    F
    class Solution {
    public:
        vector<vector<int>> levelOrderBottom(TreeNode* root) {
            
            vector<vector<int>> vv;
            std::queue<TreeNode*> q;
            TreeNode* tn;
            int n;
            
            if(root)
                q.push(root);
            
            while(!q.empty()) {
                
                n = q.size();
                std::vector<int> v;
                
                while(n) {
                    tn = q.front();
                    q.pop();
                    v.push_back(tn->val);
                    
                    if(tn->left)
                        q.push(tn->left);
                    if(tn->right)
                        q.push(tn->right);
                    n--;
                }
                
                 vv.push_back(v);
                
            }
            reverse(vv.begin(),vv.end());
            return vv; 
        
        }
    };

Log in to reply
 

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