leetcode刷题(10)——104.二叉树的最大深度

一、题目

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

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:给定二叉树 [3,9,20,null,null,15,7],
在这里插入图片描述
返回它的最大深度 3 。

二、思路及代码实现

方法一:DFS(递归)

二叉树的最大深度,等于左子树的最大深度和右子树的最大深度较大者加一,可用递归求解。

代码如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null)
            return 0;
        int l = maxDepth(root.left);
        int r = maxDepth(root.right);
        return l >= r ? (l + 1) : (r + 1);
    }
}

方法二:BFS

利用队列,对树进行层序遍历,找出树的最大层次,即为最大深度。过程如下:

  • 创建 depth(初始为 0) 变量,用来记录树的层次;
  • 创建一个队列,先将根节点入队;
  • 只要队列不为空,说明对应树的当前层不为空,则 depth + 1,然后将队列中所有的元素出队,并将它们所有的孩子入队;
  • 这样,while 每循环一次,就会处理完树中同一层的节点;
  • 最后队列为空时结束,while 循环的次数就是最大深度。

代码如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null)
            return 0;
        int depth = 0;
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()){
            depth++;
            int size = queue.size();// 注意这里不能直接用 queue.size() 进行for循环
            for(int i = 0; i < size; i++){
                TreeNode temp = queue.poll();
                if(temp.left != null)
                    queue.add(temp.left);
                if(temp.right != null)
                    queue.add(temp.right);
            }
        }
        return depth;
    }
}

有个小细节要注意:

代码中的注释部分。在用 for 循环进行出队和入队操作时,不能直接用 queue.size() 作为条件,因为循环中还会向 queue 中添加元素。

发布了56 篇原创文章 · 获赞 0 · 访问量 928

猜你喜欢

转载自blog.csdn.net/weixin_45594025/article/details/104986717