《剑指offer》JZ38二叉树的深度

JZ38:输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

解析:二叉树问题,一般都可以采用最直接的递归方法,最常用;但是面试往往会让给出非递归方法

 

代码给出两种方法:

方法1:递归方法

public int TreeDepth(TreeNode root){
     if(root == null)
         return 0;
     int left = TreeDepth(root.left);
     int right = TreeDepth(root.right);
     return Math.max(left,right) + 1;
 }

 

方法2:非递归方法:层次遍历

public int TreeDepth(TreeNode root){
     if (root == null)
         return 0;
     TreeNode current;
     Queue<TreeNode> queue = new LinkedList<TreeNode>();//构造辅助队列
     int cur, width;      //cur记录访问到当前层的第几个;width为当前层的宽度
     int deep = 0;        //初始深度为0
     queue.offer(root);   //头节点入队列
     while(!queue.isEmpty()){   //队列不为空,循环记录深度
         cur = 0;               //新的一层,cur初始值为0
         width = queue.size();  //当前队列里的节点即为该层的所有节点
         while(cur < width){    //循环访问该层的所有节点
             current = queue.poll;//访问队列的头节点
             if (current.left != null)         //左节点不为空,左节点入队列
                 queue.offer(current.left);
             if (current.right != null)         //右节点不为空,右节点入队列
                 queue.offer(current.right);
             cur++;
         }
         deep++;               // 访问完一层,层数+1;
     }
     return deep;
 }

温故而知新:方法2还可以写成下边形式

{

        if(root == null)
            return 0;
        Queue<TreeNode> q = new LinkedList<TreeNode>();
        q.offer(root);                             //首先将根节点存入q
        int level = 0;
        while(q.size() != 0){
            level++;
            for(int i = 1; i <= q.size(); i++){  //有几个结点就存几次
                TreeNode temp = q.poll();        //提取结点,即将该节点从队列中删除
                if(temp.left != null)
                    q.offer(temp.left);          //将节点左儿子存入
                if(temp.right != null)
                    q.offer(temp.right);         //将节点右儿子存入
            }
        }
        return level;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

localhost1212

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值