recursive Java solution, 5 lines

  • 0
        public void flatten(TreeNode root) {
            flatten(root, null);
        private TreeNode flatten(TreeNode node, TreeNode tail) {
            if(node == null) return tail;
            node.right = node.left == null ? flatten(node.right, tail) : flatten(node.left, flatten(node.right, tail));
            node.left = null;
            return node;

Log in to reply

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