数据结构问题"编写一个判断两颗二叉树是否相等的程序"

编写一个程序判断两棵二叉树是否是相似的,关于相似性的定义如下:这两棵二叉树或者都是空树,或者非空且有相似的左子树和右子树... 编写一个程序判断两棵二叉树是否是相似的,关于相似性的定义如下:
这两棵二叉树或者都是空树,或者非空且有相似的左子树和右子树
展开
 我来答
inee123456
2007-10-30 · TA获得超过152个赞
知道答主
回答量:270
采纳率:0%
帮助的人:220万
展开全部
2、程序源代码:
public class SimiliarTreeTest {
public static boolean test(BinNode t1,BinNode t2){
if(t1==null&&t2==null)
return true;
else if(t1!=null&&t2!=null)
{
return test(t1.left,t2.left)&&test(t1.right,t2.right);
}
return false;
}
}

3、测试类:
public class SimiliarilityTest {
public static void main(String[] args){
BST<Integer> intTree=new BST<Integer>();
BST<Character> charTree=new BST<Character>();
BST<String> strTree=new BST<String>();

Integer[] numbers={14,15,2,26,36,11,25,58,47,44,16,1};
Character[] chars={14,15,2,26,36,11,25,58,47,44,16,1};
String[] strs={"this","is ","so ","dispointed","and ","i ","am","trying"};

for(int i=0;i<strs.length;i++){
strTree.insert(new BinNode<String>(strs[i]));
}
for(int i=0;i<numbers.length;i++)
intTree.insert(new BinNode<Integer>(numbers[i]));
for(int i=0;i<chars.length;i++)
charTree.insert(new BinNode<Character>(chars[i]));

boolean b=SimiliarTreeTest.test(intTree.root, strTree.root);
System.out.println("intTree and strTree are similiar with each other?"+b);
System.out.println("-----------------");
b=SimiliarTreeTest.test(intTree.root, charTree.root);
System.out.println("intTree and charTree are similiar with each other?"+b);

}
}
(注明:其中BST为二叉查找树)
forchenyun
2007-10-29 · TA获得超过586个赞
知道小有建树答主
回答量:328
采纳率:100%
帮助的人:453万
展开全部
public boolean isSimilar(BinNode rt1,BinNode rt2){
if(rt1==null&&rt2==null)return true;
else if(rt1==null)return false;
else if(rt2==null)return false;
if(isSimilar(rt1.left(),rt2.left())&&isSimilar(rt1.right(),rt2.right()))return true;
return false;
}
其中,BinNode是节点类的接口
//这是二叉树节点的抽象数据类型(ADT)
public interface BinNode {

public Object element();

public Object setElement(Object v);

public BinNode left();

public BinNode setLeft(BinNode p);

public BinNode right();

public BinNode setRight(BinNode p);

public boolean isLeaf();

}
递归的使用可以很方便的实现程序,但也增加了程序的时间消耗.谢谢
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式