simple Java recursive solution


  • 0
    J
        public void flatten(TreeNode root) {
            dfs(root);
        }
        
        private TreeNode dfs(TreeNode root) {
            if (root == null) return null;
            TreeNode last = root;
            if (root.left != null) {
                last = dfs(root.left);
                last.right = root.right;
                root.right = root.left;
            }
            root.left = null;
            if (last.right != null) {
                last = dfs(last.right);
            }
            return last;
        }
    

Log in to reply
 

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