I am trying to intersect two binary trees, and create a new binary tree with the nodes that are the same, but the following creates a stackOverflow error. Can anyone help me?
I don't know the specific problem but there are some issues.
result
) and inserting into it, rather than global variable? Cleaning up those flaws, I get:
public OrderedSet<E> intersection(OrderedSet<E> other) {
OrderedSet<E> result = new OrderedSet<E>();
intersection(result, root, other.root);
return result;
}
private void intersection(OrderedSet<E> result, TreeNode root1,
TreeNode root2) {
if (root1 == null || root2 == null) {
return;
}
if (root1.data == root2.data) {
result.insert(root1.data);
}
intersection(result, root1.left, root2.left);
intersection(result, root1.right, root2.right);
}
I don't know if this will work, but it's closer
A stack overflow error suggests that there's recursion that's not bottoming out before the stack limit is reached. The chief suspect is the private void intersection
method. If the inputs are correct binary trees, then the condition (root1 == null || root2 == null)
should be reached at some point -- but this might be a long time for a very large, unbalanced binary tree, or never if the "binary trees" are buggy and have a cycle somewhere. Either case could be a reason for the overflow.
I'd also point out that the condition if (root1 == root2)
in the same method is probably not doing what it's intended to: the parameters root1
and root2
are probably not the same object, so that condition will almost certainly be false. Some other equals()
based comparison is probably more appropriate.