Java 5 lines simple recursive solution without loop or stack

  • 1

    The idea is to have a method that returns the tail of the list after flatten the tree.

        public TreeNode flatten(TreeNode root) {
            if (root == null) return null;
            TreeNode left = root.left, right = root.right, cur = root;
            cur.left = null;
            if (left!= null) cur = flatten(cur.right = left);
            return right != null ? flatten(cur.right = right) : cur;

Log in to reply

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