So I am working on a problem on LeetCode where I must invert a binary tree.
Problem:
and here's my solution:
class Solution {
public TreeNode invertTree(TreeNode root) {
TreeNode newTree = root;
return invertTreeHelper(root, newTree);
}
public TreeNode invertTreeHelper(TreeNode root, TreeNode newTree)
{
if(root == null)
return null;
newTree.val = root.val;
newTree.left = invertTreeHelper(root.right, newTree.left);
newTree.right = invertTreeHelper(root.left, newTree.right);
return newTree;
}
}
The given input is:
[4,2,7,1,3,6,9]
My expected output is:
[4,7,2,9,6,3,1]
However, my output is:
[4,7,7,9,6,6,9]
So clearly, my output does not work for the left side of the tree. I want to know where I went wrong. Is anyone please able to help me with this?
