繁体   English   中英

计算树上的匹配节点

[英]Counting matching nodes on a tree

我正在Practice-It上尝试这个问题,但已经有一段时间了。

编写一个方法matches,返回一棵树中与另一棵树中节点匹配的节点数的计数。 匹配被定义为相对于它们的整体根在两棵树中处于相同位置并且存储相同数据的一对节点。

到目前为止,我已经尝试了以下方法,但我不太清楚我想要的数量,我也不太确定为什么。

 public int matches(IntTree t2) { return match(overallRoot, t2.overallRoot); } public int match(IntTreeNode tree1, IntTreeNode tree2) { if(tree1 == null && tree2 == null) return 1; if(tree1 == null || tree2 == null) return 0; if(tree1.data == tree2.data) return 1; int left = match(tree1.left, tree2.left); int right = match(tree1.right, tree2.right); return left + right; }

任何帮助将不胜感激!

如果当前节点匹配,您将停止搜索。 如果不同,你检查左右,但在匹配你返回一个。

您非常接近解决方案,您必须考虑:

  • 如果其中一个节点为null您可以停止对子树的访问并返回 0
  • 如果data为两个根是不同的count是0,否则是1,并且之后可以计算出count为两个子树增加了count的两个根。

在我的建议下面作为代码:

public int match(IntTreeNode tree1, IntTreeNode tree2) {
    if(tree1 == null || tree2 == null) { return 0; }
    int count = tree1.data == tree2.data ? 1 : 0;
    int left = match(tree1.left, tree2.left);
    int right = match(tree1.right, tree2.right);
    return count + left + right; 
}

练习一的完整答案:

int matches(IntTree tree2) {
    return matches(tree2.overallRoot, this.overallRoot);
}
int matches(IntTreeNode tree1, IntTreeNode node2)
{
    int left=0, right=0, count =0;
    if(tree1 == null && this != null || this == null && tree1 != null) { return 0; }
     count = tree1.data == node2.data ? 1 : 0;
    if(tree1.left != null && node2.left !=null){
     left = matches(tree1.left, node2.left);}
    if(tree1.right != null && node2.right !=null){
     right = matches(tree1.right, node2.right);}
    return count + left + right;
}

暂无
暂无

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

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