My 3ms Cpp Solution


  • 0
    H
    class Solution {
    public:
        vector<vector<int>> levelOrder(TreeNode* root) {
            vector<vector<int>> ret;
            if (root == NULL){
                return ret;
            }
            deque<TreeNode*> q;
            q.push_back(root);
            int next = 1;
            while(1){
                vector<int> v;
                int cflag = 0;
                int nnext = 0;     //record how many elements should pop from queue for current level
                int qsize = q.size();
                
                for(int i = 0; i < qsize; i++){
                    if(q[i] != NULL){   //if all elements in queue is NULL, then break
                        cflag = 1;
                        break;
                    }
                }
                
                if(cflag == 1){
                    for(int i = 0; i < next; i++){
                        TreeNode * f = q.front(); 
                        if(f != NULL){
                            v.push_back(f->val);
                            q.pop_front();
                            q.push_back(f->left);
                            q.push_back(f->right);
                            nnext += 2;
                        }else{
                            q.pop_front();
                        }
                    }
                }else{
                    break;
                }
                
                ret.push_back(v);
                next = nnext;
            }
            return ret;
        }
    };
    

Log in to reply
 

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