【问题标题】:Check if two trees are identical检查两棵树是否相同
【发布时间】:2016-01-24 12:13:51
【问题描述】:

我创建了自己的 Tree 类,并尝试检查两棵树是否相同。但这里的问题是我正在使用这个调用:

Tree myTree = new Tree();
Tree mySecondTree = new Tree();
myTree.isIdentical(myTree, mySecondTree);

这样传有点奇怪,我想这样传:

myTree.isIdentical(mySecondTree);

isIdentical function :

class Tree<T>{
    T data;
    Tree left;
    Tree right;
    Tree(T data){
        this.data = data;
    }

    public boolean isIdentical(Tree t1, Tree t2){
        if(t1 == t2)
            return true;
        if(t1==null || t2==null)
            return false;
        return (
            (t1.data == t2.data) &&
            (isIdentical(t1.left, t2.left)) &&
            (isIdentical(t1.right, t2.right))
        );

    }
}

我尝试使用 Stack,但我有点卡住了

【问题讨论】:

  • 为什么不使用this?例如。 this.data == t2.data。这样你就不需要第一个参数。 this 关键字是对调用当前运行方法的对象的自动引用。或者,您可以直接引用data,它无论如何都会指向t1 的数据。
  • 通过默克尔树,你会在这项任务中得到提升。
  • 您接受的答案是使用递归,请编辑您的问题。
  • isIdentical 应该声明为static,或者它应该只有一个参数otherTree 来与this 引用进行比较。

标签: java recursion stack


【解决方案1】:

既然你想这样执行它

myTree.isIdentical(mySecondTree);

你可以这样做

    public boolean isIdentical(Tree t2){
       Tree t1 = this;
       return isIdentical(t1, t2);
    }

    private boolean isIdentical(Tree t1, Tree t2){
    if(t1 == t2)
        return true;
    if(t1==null || t2==null)
        return false;
    return (
        (t1.data == t2.data) &&
        (isIdentical(t1.left, t2.left)) &&
        (isIdentical(t1.right, t2.right))
    );

}

【讨论】:

    【解决方案2】:

    您可以保留递归并将 isIdentical(myTree, Othertree) 设为私有。然后将其包装在一个方法 IsIdentical(otherTree) 中,该方法使用两个参数调用该方法,并将 this(对当前对象的引用)作为第一个参数。

    【讨论】:

      【解决方案3】:

      您的数据结构允许您在经过几次检查后在左右子节点中调用修改后的isIdentical(Tree&lt;T&gt;) 方法。请记住,parentright-childleft-child 在您的代码中都是不同的 Tree 节点实例。

      public boolean isIdentical(Tree<T> that) {
      
          if (this == that)
              return true;
      
          if (that == null)
              return false;
      
          //check the equality of the current node's data for both this and that. 
          if (this.data == that.data || (this.data != null && this.data.equals(that.data))) {
              //check the left hand side of the current node for both this and that.
              if ((this.left == null && that.left == null 
                      || this.left != null && this.left.isIdentical(that.left))
                  //check the right hand side of the current node for both this and that. 
                  && (this.right == null && that.right == null 
                      || this.right != null && this.right.isIdentical(that.right))) {
                  return true;
              }
          }
      
          return false;
      }
      

      【讨论】:

        猜你喜欢
        • 2023-03-29
        • 1970-01-01
        • 1970-01-01
        • 2017-05-02
        • 1970-01-01
        • 2021-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多