Elegant C++ recursive solution with an extra stack


  • 0
    G
        TreeNode* Flatten(TreeNode* root,vector<TreeNode*> &Stack) 
        {
            if(root == NULL)
            {
                if(Stack.empty() == false)
                {
                    TreeNode *Top = Stack.back();
                    Stack.pop_back();
                    return Flatten(Top,Stack);
                }
                
                return (NULL);
            }
            
            if(root->right)
            {
                Stack.push_back(root->right);
            }
            
            TreeNode *Left = root->left;
            root->left = NULL;
            root->right = Flatten(Left,Stack);
            return (root);
        }
    
        void flatten(TreeNode* root) 
        {
            vector<TreeNode*> Stack;
            root = Flatten(root,Stack);
        }

Log in to reply
 

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