j.Doie
j.Doie

Reputation: 91

Why does this not invert the binary tree?

I'm not sure why this code to invert a binary tree does not work. It works when I invert the values instead of the actual nodes but in that case does not work if a node is null which is why I need to use the nodes for inversion.

You can uncomment the print lines to see it's hitting the correct values and changing the tree as it should be changed but it returns the original array.

    class Solution {
        public TreeNode invertTree(TreeNode root) {
            if(root == null) {
                return null;
            }
            invertBinaryTree(root.left, root.right);
            return root;
        }
        
    private static void invertBinaryTree(TreeNode l, TreeNode r) {
    if(l == null || r == null) {
        return;
    }
    
    TreeNode temp = l;
    l = r;
    r = temp;
        
//     System.out.println(l.val);
//     System.out.println(r.val);
        
    
    invertBinaryTree(l.left, r.right);
    invertBinaryTree(l.right, r.left);
        

}
}

Upvotes: 0

Views: 204

Answers (1)

samgak
samgak

Reputation: 24427

Java uses "pass by value" and not "pass by reference" for method parameters. This means that if you pass an object to a method, you can update the object's member variables inside the method and the changes will be reflected in the calling method, however if you overwrite the parameter to refer to a different object (like you are doing by changing the values of l and r) the reference to that object won't be updated in the calling method. You can rewrite your function to something like this:

private static void invertBinaryTree(TreeNode t) {
     TreeNode temp = t.left;
     t.left = t.right;
     t.right = temp;

     if(t.left != null)
         invertBinaryTree(t.left);
     if(t.right != null)
         invertBinaryTree(t.right);
}

Then you would just call it on the top of the tree by passing invertBinaryTree(root);

Upvotes: 1

Related Questions