简体   繁体   English

如果一个二叉树是另一棵树的子树

[英]If one binary tree is the subtree of another tree

I wrote this function to check if n2 is the subtree of n1 . 我写了这个函数来检查n2是否是n1的子树。 I use recursion, but when I tested it using two trees, it showed me the wrong answer (expected true , but it actually returned false ). 我使用递归,但是当我使用两棵树对其进行测试时,它显示出错误的答案(预期为true ,但实际上返回false )。

I struggled for a while but still cannot say what's wrong. 我挣扎了一段时间,但仍然不能说出什么问题。

private Boolean isSubTree(node n1, node n2){
    if(n1 == null)
        return false;
    if(n2 == null)
        return true;
    if(n1.data == n2.data){
        return isSubTree(n1.left,n2.left) && isSubTree(n2.right,n2.right);
    }
    else
        return isSubTree(n1.left, n2) || isSubTree(n1.right, n2);
}

Your edge cases are incorrect. 您的极端情况不正确。 In particular, when both n1 and n2 are null then that counts as a matching subtree, but if only one is null, then that counts as a mismatch. 特别是,当n1n2都为null时,则计为匹配子树,但是如果只有一个为null,则计为不匹配。

I think it's easier to check n2's parent to see whether or not it's n1. 我认为检查n2的父母以查看是否为n1更容易。 if not, continue all the way until you find it; 如果没有,请继续进行直到找到为止; in which case you return true. 在这种情况下,您返回true。 the alternate is that all parents up to and including the root are not n1; 备选方案是直到根(包括根)的所有父母都不是n1; in which case you return false. 在这种情况下,您返回false。 In other words, work your way up instead of checking all possible children and their children etc. of n1 to reach n2. 换句话说,您要逐步提高自己,而不是检查所有可能的子代及其子代等n1到n2。

There are two cases to consider. 有两种情况要考虑。

  1. If the subtree has to be one of the nodes of the original tree then you can scan the tree for the matching subtree node. 如果子树必须是原始树的节点之一,则可以扫描树以查找匹配的子树节点。
  2. If the subtree only has to have equal values, then you need to write a recursive tree equality function and apply it to all the leaves of the original tree in a second recursive function. 如果子树只需要具有相等的值,那么您需要编写一个递归树相等函数,并在第二个递归函数中将其应用于原始树的所有叶子。

i agree with nabau ... its better to check weather n2's and n1's root node is same if we have data for parent in node 我同意nabau ... 如果我们在节点中有父级的数据,最好检查天气n2和n1的根节点是否相同

else we can check n2's root with node of every node in n1's 否则我们可以用n1中每个节点的节点检查n2的根

in java we can compare two objects are same or not 在Java中,我们可以比较两个对象是否相同
forEach all node in n1 equals root of n2 if any is node is equal they are same fornn1中的所有节点均等于n2的根,如果任何等于node则它们相同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM