java算法比较两个二叉数是否相等_java实现二叉树查找,统计结点个数,统计树的深度及判断两棵树是否相等...

二叉树的建立在前面已经实现,现在只写子函数

public bitreeNode searchNode(bitreeNode t,Object x){

if(t!=null){

if(t.getdata().equals(x)) //对根节点进行判断

return t;

else{

bitreeNode lresult=searchNode(t.getlchild(),x); //查找左子树

//若在左子树中查找到值为x的结点,则返回该结点;否则,在右子树中查找该结点并返回结果

return lresult!=null?lresult:searchNode(t.getrchild(),x);

}

}

return null;

}

//计算二叉树中结点个数

public int countNode(bitreeNode t){

//采用先根遍历的方式对二叉树进行遍历,计算结点个数

int count=0;

if(t!=null){

count++; //根结点加1

count=count+countNode(t.getlchild()); //加上左子树结点数

count=count+countNode(t.getrchild()); //加上右子树结点数

}

return count;

}

public int countNode1(bitreeNode t){

//采用层次遍历对二叉树进行遍历

int count=0;

if(t!=null){

Linkqueue l=new Linkqueue(); //构造队列

l.offer(t); //根节点入队

while(!l.isEmpty()){

t=(bitreeNode)l.poll();

count++; //结点数目加1

if(t.getlchild()!=null) //左孩子非空,入队

l.offer(t.getlchild());

if(t.getrchild()!=null) //右孩子非空,入队

l.offer(t.getrchild());

}

}

return count;

}

public int getdepth(bitreeNode t){

if(t!=null){

int ldepth=getdepth(t.getlchild()); //左子树的深度

int rdepth=getdepth(t.getrchild()); //右子树的深度

return 1+(ldepth>rdepth?ldepth:rdepth); //返回左子树和右子树深度大的那一个

}

return 0;

}

public boolean isequal(bitreeNode t1,bitreeNode t2){

if(t1==null&&t2==null) //同时为空

return true;

if(t1!=null&&t2!=null)

if(t1.getdata().equals(t2.getdata())) //根节点值是否相等

if(isequal(t1.getlchild(),t2.getlchild())) //左子树是否相等

if(isequal(t1.getrchild(),t2.getrchild())) //右子树是否相等

return true;

return false;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值