Can someone explain why this does not work?


  • 0
    T
    public TreeNode invertTree(TreeNode root) {
        if (root == null) return null;
        
        root.left = invertTree(root.right);
        root.right = invertTree(root.left);
        return root;
           
    }

  • 0
    L

    the second line:
    root.left = invertTree(root.right);
    has changed the root.left.


  • 1
    P

    Because in the

    root.right = invertTree(root.left);
    The input parameter is wrong root.left. Its the new root.left. You can do the following it will work.

    public TreeNode invertTree(TreeNode root) {
    if (root == null) return null;

    TreeNode tempNode = root.left;
    root.left = invertTree(root.right);
    root.right = invertTree(tempNode);
    return root;
    

    }


Log in to reply
 

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