Reputation: 21
I am trying to invert a binary tree as in Java:
class Solution {
TreeNode node;
public TreeNode invertTree(TreeNode root)
{
if(root == null)
return null;
node = root;
node.left = invertTree(root.right);
node.right = invertTree(root.left);
return node;
}
}
However on running this code I am getting a stackoverflow error. Can anyone explain why?
Upvotes: 1
Views: 99
Reputation: 21
After inverting left subtree and right subtree, you need to swap the left node and right node too to make an inverted binary tree. You just need to add the code of swap two values.
class Solution {
TreeNode node;
public TreeNode invertTree(TreeNode root)
{
if(root == null)
return root;
invertTree(root.left);
invertTree(root.right);
TreeNode temp=root.left;
root.left=root.right;
root.right=temp;
return node;
}
}
Upvotes: 0
Reputation: 6017
You need to create new nodes and replace them while parsing. You are trying to use one TreeNode object to do so, therefore you never reach your base condition.
To understand better, please use a pretty print method and call it from this method and observe the change on small input.
public TreeNode invertTree(TreeNode root) {
if (root == null){
return root;
}
TreeNode right = invertTree(root.right);
TreeNode left = invertTree(root.left);
root.left = right;
root.right = left;
return root;
}
The inverse of a tree with root r, and subtrees right and left, is a tree with root r, whose right subtree is the inverse of left, and whose left subtree is the inverse of right.
Upvotes: 1