1. 程式人生 > 實用技巧 >104-二叉樹的最大深度

104-二叉樹的最大深度

題目描述

給定一個二叉樹,找出其最大深度。

二叉樹的深度為根節點到最遠葉子節點的最長路徑上的節點數。

說明: 葉子節點是指沒有子節點的節點。

示例:

給定二叉樹 [3,9,20,null,null,15,7],

3

/ \

9 20

/ \

15 7

返回它的最大深度 3 。

連結:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree

思路:

(1)樹形DP

(2)考慮邊界

(3)左右子樹對當前節點的影響

(4)根據左右子樹計算當前節點值

(5)返回當前節點結果

程式碼

public int maxDepth(TreeNode root) {
        if(root == null) {
            return 0;
        }
        if(root.left == null && root.right == null) {
            return 1;
        }

        int maxLeftDepth = Integer.MIN_VALUE;
        int maxRightDepth = Integer.MIN_VALUE;
        if(root.left != null) {
            maxLeftDepth = maxDepth(root.left);
        }
        if(root.right != null) {
            maxRightDepth = maxDepth(root.right);
        }
        int maxDepth = Math.max(maxLeftDepth, maxRightDepth);
        return maxDepth + 1;
    }