我想交叉兩個二叉樹,並創建一個新的二叉樹與相同的節點,但以下創建一個stackOverflow錯誤。誰能幫我?2個二叉樹的交集拋出堆棧溢出錯誤
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);
}
你的樹有多大?你能否達到最大遞歸深度? – nbrooks
我正在測試的樹很小,有4-5個節點。 – Tinkerbell
這是我的測試。 – Tinkerbell