104. 二叉树的最大深度


104. 二叉树的最大深度

难度简单 806
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7]
    3
   /
  9  20
    /  
   15   7
返回它的最大深度  3 。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int maxDepth1(TreeNode root) {
        if (root == null) {
            return 0;
        } else {
            int leftHeight = maxDepth(root.left);
            int rightHeight = maxDepth(root.right);
            return Math.max(leftHeight, rightHeight) + 1;
        }
    }
}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        int ans = 0;
        while (!queue.isEmpty()) &#123;
            int size = queue.size();
            while (size > 0) &#123;
                TreeNode node = queue.poll();
                if (node.left != null) &#123;
                    queue.offer(node.left);
                &#125;
                if (node.right != null) &#123;
                    queue.offer(node.right);
                &#125;
                size--;
            &#125;
            ans++;
        &#125;
        return ans;
    &#125;
// 作者:LeetCode-Solution
// 链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/solution/er-cha-shu-de-zui-da-shen-du-by-leetcode-solution/

&#125;

广度优先搜索

思路与算法
我们也可以用「广度优先搜索」的方法来解决这道题目,但我们需要对其进行一些修改,此时我们广度优先搜索的队列里存放的是「当前层的所有节点」。每次拓展下一层的时候,不同于广度优先搜索的每次只从队列里拿出一个节点,我们需要将队列里的所有节点都拿出来进行拓展,这样能保证每次拓展完的时候队列里存放的是当前层的所有节点,即我们是一层一层地进行拓展,最后我们用一个变量 ans 来维护拓展的次数,该二叉树的最大深度即为 ans。


文章作者:   future
版权声明:   本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 future !
 上一篇
674. 最长连续递增序列 674. 最长连续递增序列
674. 最长连续递增序列难度简单 172给定一个未经排序的整数数组,找到最长且**  连续递增的子序列,并返回该序列的长度。**连续递增的子序列 可以由两个下标 l 和 r(l < r)确定,如果对于每个 l <= i <
下一篇 
69. x 的平方根 69. x 的平方根
69. x 的平方根难度简单 605实现 int sqrt(int x) 函数。计算并返回 x 的平方根,其中 x *是非负整数。由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。*示例 1:**输入: 4输出: 2 示例 2:输
  目录