题解 | #二叉树的最大深度#

二叉树的最大深度

https://www.nowcoder.com/practice/8a2b2bf6c19b4f23a9bdb9b233eefa73

思路

使用深度优先遍历遍历二叉树的同时统计二叉树的最大深度 当然也可以利用层序遍历来计算二叉树的最大深度(记录层数)

代码

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
    * @param root TreeNode类
    * @return int整型
    */
    public int maxDepth(TreeNode root) {
        return DFS(root, 0);
    }

    /**
     * 深度优先遍历
     *
     * @param root  根节点
     * @param depth 深度
     * @return int 最大深度
     * @apiNote
     * @since 2022/12/30 21:02
     */
    public int DFS(TreeNode root, int depth) {
        if (root != null) {
            // 深度自增
            depth++;
            // 创建变量接收左右子树最大深度
            int leftDepth = depth;
            int rightDepth = depth;
            if (root.left != null) {
                // 如果左子树不为空
                leftDepth = DFS(root.left, depth);
            }
            if (root.right != null) {
                // 如果右子树不为空
                rightDepth = DFS(root.right, depth);
            }
            // 比较本层与左右子树最大深度,防止无左右子树导致返回的层数为0
            return Math.max(Math.max(leftDepth, rightDepth), depth);
        }
        return depth;
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务