Recursive solution, but no global variable and no while search


  • 0
    C
    public void flatten(TreeNode root) {
        if (root == null) {
            return;
        }
        helper(root, root.left); 
    }
    
    private TreeNode helper(TreeNode last, TreeNode next) {
        if (last == null) {
            return last;
        }
       
        TreeNode temp = last.right;
        if (next != null) {
            last.right = next;
            
            TreeNode nextLeftLast = helper(next, next.left);
            last.left = null;
            
            TreeNode nextRightLast = helper(nextLeftLast, temp);
            
            return nextRightLast;    
        } else {
            if (last.right != null) {
                last.right = null;
                TreeNode lastRightLast = helper(last, temp);
                return lastRightLast;
            }
            return last;
        }
    }

Log in to reply
 

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