My 8ms solution using inOrder traversal, easy to undersand


  • 0
    X
    class Solution {
    public:
    void flatten(TreeNode* root) {
        if(!root)return;
        helper(root);
       
        while(root)
        {
            root->right=root->left;
            root->left=NULL;
            root=root->right;
        }
        
        
        
    }
    void helper(TreeNode* root)
    {
        if(!root)return;
        helper(root->left);
        if(root->right&&root->left)
        {
            TreeNode* temp=root;
            while(temp->left)
            {
                temp=temp->left;
            }
            temp->left=root->right;
        }
        else if(root->right&&!root->left)
            root->left=root->right;
        helper(root->right);
    }
    
    
    };

Log in to reply
 

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