【发布时间】:2014-10-16 18:06:24
【问题描述】:
我在递归搜索另一个子树时遇到了严重问题。
我试试这个,但是...
public static boolean containsTree (Node t1, Node t2)
{
if (t2 == null)
return true;
// Empty tree is always a subtree.
else
return subTree(t1, t2);
}
public static boolean subTree (Node t1, Node t2)
{
if (t1 == null)
return false; // Big tree is over.
if (t1.getName().equalsIgnoreCase(t2.getName()))
return matchTree(t1, t2);
return (subTree(t1.getChild(), t2) || subTree(t1.getBrother(), t2));
}
private static boolean matchTree (Node t1, Node t2)
{
if (t1 == null && t2 == null)
return true; // Both trees are empty.
if (t1 == null || t2 == null)
return false; // Big tree empty and subtree still not found.
if (!t1.getName().equalsIgnoreCase(t2.getName()))
return false;
return (matchTree(t1.getChild(), t2.getChild()) && matchTree(
t1.getBrother(), t2.getBrother()));
}
似乎格式不正确。 containsTree函数,当找到一个不同的节点时停止搜索。
您可以在下面找到两棵树的示例。
1
/ \ 3
/ \ /\
/ \ / \
2 3 7 8
/\ /\
/ \ / \
3 4 5 6
\
3
/\
/ \
7 8
在这种情况下,当函数比较右边的子树和左边的子树时,当find等于父节点但有不同的子节点时停止搜索。 我需要该函数不要停止搜索,而是抛出这一点并搜索所有其他子节点及其子树。
【问题讨论】:
-
最简单的方法是按顺序获取两棵树,然后比较它们。阅读ordering。
-
迭代小树中的元素并确定大树是否包含所有元素。如果任何元素不在较大的树中...它不是子集...
-
他的意思是当它找到第一个节点3时如果左右不同则不继续搜索子树而是丢弃整个子树
-
我不认为您可以拥有具有重复节点的有效二叉树。这将使搜索变得不可能。
标签: java recursion tree binary-tree