Java中的二叉树相等方法 [英] binary Tree equal method in java

查看:71
本文介绍了Java中的二叉树相等方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨 我编写了一个检查两个二叉树是否相等的函数

我不知道它的正确与否请帮忙!

 公共 静态 布尔 equal(BinaryNode t1,BinaryNode t2){
      如果(t1 == null || t2 == null)返回 false;
      其他 如果(t1.element!= t2.element)返回 false;
      其他 如果(等于(t1.left,t2.left))其他 如果(等于(t1.right,t2.right))其他
          返回 true;

  }

解决方案

首先,我对类BinaryNode并不熟悉,所以我猜想它是您自己的.
我要采用的方法是使类实现equals方法:

  public   class  BinaryNode {

    // 东西

    公共  int  equals(Object obj){
        如果( == obj){
          返回 true;
        }
        如果(obj == null ||!(obj  instanceof  BinaryNode)){
            返回 false;
        }

        BinaryNode =(BinaryNode)obj;
        如果( .element.equals(that.element)){
            返回 false;
        }
        其他 如果( .left == null ||  .left.equals(that.left)){
            返回 false;
        }
        其他 如果(.正确== null ||  .right.equal(that.right)){
            返回 false;
        }
        // 必须相同
        返回 true;
    }

} 


hi i coded a function that checks two binary tree are equal or not

i dont know its correct or not please help!

public static boolean equal(BinaryNode t1, BinaryNode t2){
      if(t1==null || t2==null) return false;
      else if(t1.element != t2.element) return false;
      else if(equal(t1.left,t2.left)) return false;
      else if(equal(t1.right,t2.right)) return false;
      else
          return true;

  }

解决方案

Firstly, I am not familiar with the class BinaryNode so I would guess it is your own.
The approach I would take is to make the class implement the equals method:

public class BinaryNode {

    // stuff

    public int equals(Object obj) {
        if (this == obj) {
          return true;
        }
        if ( obj == null || !(obj instanceof BinaryNode)) {
            return false;
        }

        BinaryNode that = (BinaryNode)obj;
        if (this.element.equals(that.element)) {
            return false;
        }
        else if (this.left == null || this.left.equals(that.left)) {
            return false;
        }
        else if (this.right == null || this.right.equal(that.right)) {
            return false;
        }
        // must be the same
        return true;
    }

}


这篇关于Java中的二叉树相等方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆