我正在尝试使两棵二叉树相交,并使用相同的节点创建一棵新的二叉树,但以下会产生 stackOverflow 错误。谁能帮我?
private OrderedSet<E> resultIntersect = new OrderedSet<E>();
public OrderedSet<E> intersection(OrderedSet<E> other) {
OrderedSet<E> result = new OrderedSet<E>();
if (other.root == null || root == null)
return result;
else if (height() == 0 && other.height() == 0
&& other.root.data.equals(root.data)) {
result.insert(root.data);
return result;
} else {
intersection(other, root, other.root);
result = resultIntersect;
}
return result;
}
private void intersection(OrderedSet<E> other, TreeNode root1,
TreeNode root2) {
if (root1 == root2) {
resultIntersect.insert(root1.data);
}
if (root1 == null || root2 == null) {
return;
}
intersection(other, root1.left, root2.left);
intersection(other, root1.right, root2.right);
}
编辑
我觉得这更接近我需要的方式,但我仍然得到错误。
private OrderedSet<E> resultIntersect = new OrderedSet<E>();
public OrderedSet<E> intersection(OrderedSet<E> other) {
OrderedSet<E> result = new OrderedSet<E>();
result = resultIntersect;
return result;
}
private void intersection(OrderedSet<E> other, TreeNode t) {
if (other.contains(t.data)) {
resultIntersect.insert(t.data);
}
if(t.left != null)
intersection(other, t.left);
if(t.right != null)
intersection(other, t.right);
}