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 intersection(OrderedSet other) {
OrderedSet result = new OrderedSet();
intersection(result, root, other.root);
return result;
}
private void intersection(OrderedSet 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