Any one know why a dummy tree root doesn't work? Thank you


  • 0
    H
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public TreeNode dummyRoot = new TreeNode(0);
        public void flatten(TreeNode root) {
            preorderHelper(root);
            root = dummyRoot.right;
        }
        public void preorderHelper(TreeNode root) {
            if (root == null) return;
            dummyRoot.right = new TreeNode(root.val);
            dummyRoot = dummyRoot.right;
            preorderHelper(root.left);
            preorderHelper(root.right);
        }
    }
    

    I know the original tree didn't be modified. But can't I just replace the original tree with a new one?

    This methods show such details:
    Input:
    [1,2]
    Output:
    [1,2]
    Expected:
    [1,null,2]

    Please figure out my problems, thank you.


Log in to reply
 

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