gpt4 book ai didi

java - 检查两棵树是否相同

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:45:45 28 4
gpt4 key购买 nike

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

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

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

myTree.isIdentical(mySecondTree);

isIdentical 函数:

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,但我有点卡在这上面

最佳答案

既然要这样执行

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

}

关于java - 检查两棵树是否相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33328083/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com