Why the first is AC,the second is WA


  • 0
    T
    public class Solution {
                public TreeNode invertTree(TreeNode root) {
                    if(root==null){
                        return root;
                    }
                    //TreeNode left=root.left;
                    //TreeNode right=root.right;
                    if(root.left==null&&root.right==null){
                        return root;
                    }
                    TreeNode temp=root.left;
                    root.left=root.right;
                    root.right= temp;
                    if(root.left!=null)
                       invertTree(root.left);
                    if(root.right!=null)
                       invertTree(root.right);
                    return root;
                }
            }
    

    why!!!!!!!!!!

    public class Solution {
            public TreeNode invertTree(TreeNode root) {
                if(root==null){
                    return root;
                }
                TreeNode left=root.left;
                TreeNode right=root.right;
                if(left==null&&right==null){
                    return root;
                }
                TreeNode temp=left;
                left=right;
                right= temp;
                if(left!=null)
                   invertTree(left);
                if(right!=null)
                   invertTree(right);
                return root;
            }
        }

  • 0

    Input: [4,2,7,1,3,6,9]
    Output: [4,2,7,1,3,6,9]
    Expected: [4,7,2,9,6,3,1]

    You can see that the Input and Output are exactly the same.
    So actually root didn't change at all.
    Because left and right are new instance of TreeNode. They points to the same object as root.left and root.right. But they do not belong to root.

    If you insist to write like that, you should return a new instance of TreeNode with left and right as its children. You can add this to the end part:

    TreeNode newNode=root;
    newNode.left=left;
    newNode.right=right;
    return newNode;

Log in to reply
 

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