【问题标题】:Checking if 2 Binary search trees are equal检查2个二叉搜索树是否相等
【发布时间】:2020-07-26 17:46:40
【问题描述】:

我正在创建一个二叉搜索树项目,其中一个问题是创建 2 棵树并检查它们是否相等。当我实现该方法时,我不断得到 firstTree 和 secondTree 是相等的。以下是相关代码:

BstTest2 firstTree = new BstTest2();
firstTree.addNode(50, "Francisco Domingo Carlos Andres Sebastián d'Anconia");
firstTree.addNode(25, "John Galt");
firstTree.addNode(15, "Hugh Akston");
firstTree.addNode(30, "Ragnar Danneskjöld");
firstTree.addNode(85, "Hank Reardan"); //implementing add method

BstTest2 secondTree = new BstTest2();
secondTree.addNode(50, "Francisco Domingo Carlos Andres Sebastián d'Anconia");
secondTree.addNode(25, "John Galt");
secondTree.addNode(15, "Hugh Akston");
secondTree.addNode(30, "Ragnar Danneskjöld");
secondTree.addNode(75, "Midas Mulligan");
secondTree.addNode(85, "Hank Reardan");

if(firstTree.isEqual(secondTree))
{
     System.out.println("firstTree and secondTree are equal");
}
else
{
     System.out.println("firstTree and secondTree are not equal");
}

比较树的 isEqual 和检查方法

public boolean isEqual(BstTest2 tree1)
{
    return check(this.rootNode, tree1.rootNode);
}
public boolean check(Node node1, Node node2)
{
    if((node1 == null) && (node2 == null))
    {
        return true;
    } 
    else if((node1 == null) || node2 != null)
    {
        return false;
    } 
    else if((node1 != null) || node2 == null)
    {
        return false;
    } 
    else
    {
        return check(node1.leftChild, node2.leftChild) && check(node1.rightChild, node2.rightChild);
    }
}

我在我的 isEqual() 和 check() 方法中做错了什么,当树不相等时,我不断得到“firstTree 和 secondTree 相等”?

【问题讨论】:

  • 你不检查节点的内容是否相等,而只是检查节点是否为null或不是null

标签: java binary-search-tree


【解决方案1】:

您忘记检查node1node2 的值是否相同。

  • 如果不一样,则表示这两棵树不一样。
  • 如果它们相同,我们会继续检查它们的左右孩子是否相同。

public boolean check(Node node1, Node node2)
{
    if((node1 == null) && (node2 == null))
    {
        return true;
    } 

    // If only one node is null, it means these two trees are not the same
    // These two nodes here couldn't both be null because we check this condition earlier.
    if(node1 == null || node2 == null)
    {
        return false;
    } 

    // Check if the value of node1 and node2 are the same
    if(node1.val != node2.val)
    {
        return false;
    } 

    return check(node1.leftChild, node2.leftChild) && check(node1.rightChild, node2.rightChild);
}

【讨论】:

  • 谢谢!我有一种感觉,我犯了一个非常愚蠢的错误哈哈
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-16
  • 2019-04-09
  • 1970-01-01
  • 2018-08-10
  • 2016-03-06
  • 2020-04-07
  • 1970-01-01
相关资源
最近更新 更多