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

来源:互联网 发布:老虎机源码 编辑:程序博客网 时间:2024/04/29 11:14

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

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++;   //根结点加1count=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++;     //结点数目加1if(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;}



阅读全文
0 0
原创粉丝点击