Recursive easy to understand


  • 0
    N

    A simple recursive solutions. It's not the best in terms of runtime, but easy to comprehend.

    public class Solution {
     
        public void flatten(TreeNode root) {
            rotate(root);
            return;
        }
        
    
        void rotate(TreeNode root) {
            //TreeNode r = null;
            TreeNode temp = null;
            
            if(root !=null){
                // Fix left most child
                rotate(root.left);
                //assign left sub tree to right
                if(root.left != null){
                    temp = root.left;
                    // append right subtree to the rightmost node of left
                    while(temp.right != null){
                        temp = temp.right; 
                    }
                    temp.right = root.right;
                    root.right = root.left;
                    root.left = null;
                }
                // Fix right child
                rotate(root.right);  
            }
        }
        
    }
    

Log in to reply
 

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