How is this recursive solution ? Any improvements?


  • 1
    A
    class Solution {
    public:
    void flatten(TreeNode *root) {
        
        root = util(root);
    }
    
    TreeNode *util(TreeNode *p){
        if(!p)
            return p;
            
        if(p->left==NULL && p->right==NULL)
            return p;
            
        if(p->left && p->right){
            
            TreeNode *l,*r;
            l=util(p->left);
            r=util(p->right);
            
            p->right = l;
            while(l->right){
                l = l->right;
            }
            l->right = r;
            
            p->left = NULL;
            return p;
        }
        
        if(p->left){
            p->right = util(p->left);
            p->left = NULL;
            return p;
        }
        
        if(p->right){
            p->right = util(p->right);
            return p;
        }
            
    }
    

    };


Log in to reply
 

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