12m C++ using stack


  • 0
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    #include <stack>
    using namespace std;
    
    class Solution {
    public:
        vector<int> largestValues(TreeNode* root) {
            vector<int> result;
            
            if(!root)
            {
                return result;
            }
            
            stack<TreeNode*> parentStack;
            stack<TreeNode*> childrenStack;
            
            parentStack.push(root);
            result.push_back(root->val);
            
            while(!parentStack.empty())
            {
                TreeNode* cur = parentStack.top();
                parentStack.pop();
                
                if(cur->left)
                {
                    childrenStack.push(cur->left);
                }
                if(cur->right)
                {
                    childrenStack.push(cur->right);
                }
                
                if(parentStack.empty() && !childrenStack.empty())
                { 
                    TreeNode* node = childrenStack.top();
                    int largest = node->val;
    
                    parentStack = childrenStack;
                    
                    while(!childrenStack.empty())
                    {
                        TreeNode* child = childrenStack.top();
                        childrenStack.pop();
                        
                        if(child->val > largest)
                        {
                            largest = child->val;
                        }
                    }
                    
                    result.push_back(largest);
                }
            }
            
            return result;
        }
    };
    

Log in to reply
 

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