【问题标题】:Counting matching nodes on a tree计算树上的匹配节点
【发布时间】:2020-03-08 13:50:44
【问题描述】:

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

编写一个方法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) 是相等的?另外,当两个树节点具有相同的数据时,为什么要返回,即使它们的子树可能有更多匹配项?

标签: java tree binary-tree binary-search-tree


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    • 如果其中一个节点是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; 
    }
    

    【讨论】:

      【解决方案3】:

      练习一的完整答案:

      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;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-12
        • 1970-01-01
        • 1970-01-01
        • 2012-10-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多