前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >二叉树的最大深度

二叉树的最大深度

作者头像
一份执着✘
发布2018-06-04 16:52:42
9060
发布2018-06-04 16:52:42
举报
文章被收录于专栏:赵俊的Java专栏赵俊的Java专栏

题意

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的距离。

样例

给出一棵如下的二叉树:

代码语言:javascript
复制
  1
 / \ 
2   3
   / \
  4   5

这个二叉树的最大深度为 3.

思路

递归法

用递归分别遍历每个节点 ,返回相对于当前节点的最大深度(记得加上根节点)。

循环法

非递归写法可以用一个队列来存储,先将根节点存入,并记录当前节点的兄弟节点个数(指来自同一个父节点),当兄弟节点都出队列完毕,就对子节点进行与根节点同样的操作。

代码实现

递归法

代码语言:javascript
复制
/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: An integer.
     */
    public int maxDepth(TreeNode root) {
        if (root == null)
            return 0;
            
        int left = maxDepth(root.left);
        int right = maxDepth(root.right);
        return Math.max(left, right) + 1;
    }
    
    //简化写法的话,其实可以一行代码解决:
    // return root == null ? 0 : Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}

循环法

代码语言:javascript
复制
/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: An integer.
     */
    public int maxDepth(TreeNode root) {
        if (root == null)
            return 0;
            
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        int depth = 0;  //表示二叉树的深度
        int count = 0;  //表示已从队列中取出当前层的个数
        int amount = 1; //表示当前节点的兄弟节点个数
        
        while (queue.size() != 0) {
            TreeNode top = queue.poll();
            count++;
            if (top.left != null) {
                queue.add(top.left);
            }
            
            if (top.right != null) {
                queue.add(top.right);
            }    
            
            if (count == amount) {
                amount = queue.size();
                count = 0;
                depth++;
            }
        }
        return depth;
    }
}

原题地址

LintCode:二叉树的最大深度

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-08-212,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题意
  • 样例
  • 思路
    • 递归法
      • 循环法
      • 代码实现
        • 递归法
          • 循环法
          • 原题地址
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档