C++ 6ms using deque, no recursion, ez to understand


  • 0
    F
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> result;
        vector<int> temp;
        if(!root) return result;
        deque<TreeNode*> d;
        d.push_back(root);  // intialize
        while(d.size()!=0){
            int n = d.size();
            for(int i = 0;i<n;i++){
                TreeNode* tem = d.front();   
                temp.push_back(tem->val);
                d.pop_front();
                if(tem->left){
                    d.push_back(tem->left);
                }
                if(tem->right){
                    d.push_back(tem->right);
                }
            }
            result.push_back(temp);
            temp.clear();
        }
        return result;
    }

Log in to reply
 

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