Intuitive Java solution


  • 0
    C
    public class Solution {
        public void flatten(TreeNode root) {
            helper(root);
        }
        //flattern the tree to a linked list and return the tail of linked list
        public TreeNode helper(TreeNode root) {
            if (root==null) return null;
            TreeNode left = root.left;
            TreeNode right = root.right;
            TreeNode left_flat = helper(left);
            TreeNode right_flat = helper(right);
            if (left_flat!=null) {
                left_flat.right = right;
                root.right = left;
            }
            root.left = null;
            return right_flat==null?(left_flat==null?root:left_flat):right_flat;
        }
    }
    

Log in to reply
 

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