检查两棵树是否相同

时间:2015-10-25 09:20:15

标签: java recursion stack

我已经创建了自己的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,但我有点困在这个

3 个答案:

答案 0 :(得分:5)

因为你想以这种方式执行

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

}

答案 1 :(得分:3)

您的数据结构允许您在几次检查后在左右子节点中调用修改后的isIdentical(Tree<T>)方法。请记住,右子左子都是代码中不同的树节点实例。

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

答案 2 :(得分:2)

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