Queue containing Level Information, C++


  • 0
    A
    class Solution {
    public:
        vector<vector<int>> levelOrder(TreeNode* root) {
            vector<vector<int>> solution;
            if(root == NULL) return solution;
            queue<pair<TreeNode*, int>> q;
            q.push(make_pair(root,1));
            while(!q.empty()){
                
                pair<TreeNode*,int> curr = q.front();
                q.pop();
                int level = curr.second;
                if(solution.size() < level){
                    vector<int> temp = {curr.first->val};
                    solution.push_back(temp);
                }
                else{
                    solution[level-1].push_back(curr.first->val);
                }
                if(curr.first->left != NULL)
                    q.push(make_pair(curr.first->left,level+1));
                if(curr.first->right != NULL)
                    q.push(make_pair(curr.first->right,level+1));
            }
            
            return solution;
            
        }
    };
    

Log in to reply
 

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