【发布时间】: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引用进行比较。