Easy to understand 1ms recursive Java solution


  • 0
    M
    public class Solution {
    public void flatten(TreeNode root) {
        if(root == null) return;
        flattenAndLeaf(root);
    }
    
    private TreeNode flattenAndLeaf(TreeNode root) {
        if(root == null) return null;
        if(root.left == null && root.right == null) return root;
        TreeNode left = root.left;
        TreeNode right = root.right;
        root.left = null;
        TreeNode leftLeaf = flattenAndLeaf(left);
        TreeNode rightLeaf = flattenAndLeaf(right);
        if(leftLeaf != null) {
            leftLeaf.right = right;
            root.right = left;
        }
        if(rightLeaf != null) return rightLeaf;
        if(right != null) return right;
        if(leftLeaf != null) return leftLeaf;
        if(left != null) return left;
        return root;
    }
    }

Log in to reply
 

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