C++ level order traversal


  • 0
    D
        vector<int> largestValues(TreeNode* root) {
            vector<int> results;
            queue<TreeNode*> myQ;
            if(root==NULL)
                return results;
            myQ.push(root);
            while(!myQ.empty())
            {
                int size = myQ.size();
                int maxVal = INT_MIN;
                while(size)
                {
                    TreeNode *temp = myQ.front();
                    myQ.pop();
                    maxVal = (temp->val) >= maxVal? (temp->val):maxVal;
                    if(temp->left!=NULL)
                        myQ.push(temp->left);
                    if(temp->right!=NULL)
                        myQ.push(temp->right);
                    size--;
                }
                results.push_back(maxVal);
            }
            return results;
        }
    

Log in to reply
 

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