我试图将两个二叉树相交,并使用相同的节点创建一个新的二叉树,但以下内容会产生 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);
}
Edit
我觉得这更接近我需要的方式,但我仍然收到错误。
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);
}
我不知道具体问题,但有一些问题。
- 为什么“其他”被传递到第二个交叉点(它从未被使用过)?
- 插入集合后不应该返回吗?
- 你不应该传入本地 OrderedSet (称为
result
)并插入其中,而不是全局变量?
- 您不应该比较 root1 和 root2 的数据而不是节点本身吗?
- 第二次返回是多余的
- 你取消引用根before你测试 null
- 初始测试是不必要的
清理这些缺陷,我得到:
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);
}
我不知道这是否有效,但它更接近
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)