【问题标题】:Program to check whether two trees are duplicates or not检查两棵树是否重复的程序
【发布时间】:2021-12-05 22:45:12
【问题描述】:

我在检查两棵树是否重复的方法时遇到问题。即使两棵树都包含相同的东西,它似乎每次都返回“不重复”。我将包括duplicateCheck 方法和我的主要方法。我不知道代码在哪里不正确,或者问题出在我的 main 方法和两棵树的声明中。

public boolean duplicateCheck(BinarySearchTree otherTree)
{
        return duplicateCheck(this.root, otherTree.getRoot());
}

  protected boolean duplicateCheck(TreeNode t1, TreeNode t2)
{
        if ((t1 == null) && (t2 == null))
        return true;


        else if (countNodes(t1) != countNodes(t2))
        return false;

        else {

        KeyedItem key1 = (KeyedItem) t1.getItem();
        KeyedItem key2 = (KeyedItem) t2.getItem();
        String s1 = (String) key1.getKey();
        String s2 = (String) key2.getKey();

        if (! s1.equals(s2) )
        return false;

        else
        return (duplicateCheck(t1.getLeft(), t2.getLeft()) && duplicateCheck(t1.getRight(), t2.getRight()) );
}
}

import java.util.*;

public class MyTree
{
        public static void main(String[] args) throws CloneNotSupportedException
        {

        BinarySearchTree t1 = new BinarySearchTree();

        t1.insert(new KeyedItem("M"));
        t1.insert(new KeyedItem("J"));
        t1.insert(new KeyedItem("D"));
        t1.insert(new KeyedItem("F"));
        t1.insert(new KeyedItem("L"));
        t1.insert(new KeyedItem("W"));
        t1.insert(new KeyedItem("S"));
        t1.insert(new KeyedItem("T"));
        t1.insert(new KeyedItem("Z"));


        BinarySearchTree t2 = (BinarySearchTree) t1.clone();

        t2.insert(new KeyedItem("M"));
        t2.insert(new KeyedItem("J"));
        t2.insert(new KeyedItem("D"));
        t2.insert(new KeyedItem("F"));
        t2.insert(new KeyedItem("L"));
        t2.insert(new KeyedItem("W"));
        t2.insert(new KeyedItem("S"));
        t2.insert(new KeyedItem("T"));
        t2.insert(new KeyedItem("Z"));


        if (t1.duplicateCheck(t2))
                System.out.println("Duplicates");
        else
                System.out.println("Not Duplicates");



}
}

【问题讨论】:

  • 在我看来,您将所有内容都放入 t2 两次。我希望它与t1 不同。
  • 您大概是指使用 t1.clone() 后跟一堆插入。
  • 是的,OP 正在复制整个树,然后第二次插入所有元素。

标签: java tree


【解决方案1】:

一般来说,解决这类问题的最佳方法是编写单元测试以确保每个方法都完全符合您的预期,然后,如果您仍然找不到问题,请使用交互式调试器。我怀疑使用这种方法你会很快发现你的问题,而且它们是你在任何情况下都需要的技能。

你的代码有很多问题

  1. 您在创建 t2 时正在克隆 t1。如果您尝试测试您的方法,您应该将其创建为新树(即new BinarySearchTree())。 clone 是一种仅应在非常特殊的情况下(如果有的话)使用的方法。
  2. 您正在检查 t1 和 t2 是否都为空,但您没有单独检查每一个。除非 countNodes 发现此问题,否则您将在 getItem 上获得 NPE。
  3. 不需要大量使用铸造。 BinarySearchTree 应该是通用的,或者 getter 应该返回正确的类型。

【讨论】:

    猜你喜欢
    • 2016-01-24
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多