My solution using a queue


  • 1
    M
    class Solution {
    public:
        vector<vector<int> > levelOrder(TreeNode *root) {
            vector<vector<int>> result;
            vector<int> row;
            if(root==NULL) return result;
            queue<TreeNode*> nodes;
            int level = 0;
            int order = 0;
            int next = 0;
            int count = 1;
            nodes.push(root);
            while(!nodes.empty()){
                TreeNode* current = nodes.front();
                row.push_back(current->val);
                order++;
                if(current->left!=NULL) {nodes.push(current->left); next++;}
                if(current->right!=NULL) {nodes.push(current->right); next++;}
                nodes.pop();
                if(order == count){
                    level++;
                    order = 0;
                    count = next;
                    next = 0;
                    result.push_back(row);
                    row.clear();
                }
                
            }
            return result;
        }
    };

Log in to reply
 

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