Fastest solution?


  • 0
    A

    I see many solutions posted here, but they seem to visit same node multiple times, thus I'd like to share my solution that visits each node only once.

    void flatten(TreeNode* root) {
        
        if(!root)
            return;
                  
        dfs(root);           
    }
    
    TreeNode* dfs(TreeNode* n){
        
        TreeNode* l = n->left;
        TreeNode* r = n->right;       
        
        if(!l&&!r){
           return n;
        }
        
        if(l){
            n->left = nullptr;
            n->right = l;
        
            TreeNode* last = dfs(l);
            last->right = r; 
        }
         
        if(r)   
            dfs(r);        
        
    }

Log in to reply
 

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