求二叉树的深度 递归 非递归

 public int findDeep1(BiTree root)  
  {  
      
      if(root == null)  
      {  
          return 0;  
      }  
      else  
      {  
       int lchilddeep = findDeep1(root.left);//求左子树的深度  
       int rchilddeep = findDeep1(root.left);//求右子树的深度  
       return lchilddeep > rchilddeep ? lchilddeep + 1 : rchilddeep + 1;//左子树和右子树深度较大的那个加一等于整个树的深度  
      }  
  }  





  public int findDeep2(BiTree root)  
  {  
     if(root == null)  
         return 0;  
      
     BiTree current = null;  
     LinkedList<BiTree> queue = new LinkedList<BiTree>();  
     queue.offer(root);  
     int cur,last;  
     int level = 0;  
     while(!queue.isEmpty())  
     {  
         cur = 0;//记录本层已经遍历的节点个数  
         last = queue.size();//当遍历完当前层以后,队列里元素全是下一层的元素,队列的长度是这一层的节点的个数  
         while(cur < last)//当还没有遍历到本层最后一个节点时循环  
         {  
             current = queue.poll();//出队一个元素  
             cur++;  
             //把当前节点的左右节点入队(如果存在的话)  
             if(current.left != null)  
             {  
                 queue.offer(current.left);  
             }  
             if(current.right != null)  
             {  
                 queue.offer(current.right);  
             }  
         }  
         level++;//每遍历完一层level+1  
     }  
     return level;  
  } 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值