104. Maximum Depth Of Binary Tree



104. Maximum Depth Of Binary Tree (Easy) 栈的最大深度

题干

Given the root of a binary tree, return its maximum depth.

A binary tree’s maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Example 1:

img

Input: root = [3,9,20,null,null,15,7]
Output: 3

Example 2:

Input: root = [1,null,2]
Output: 2

Constraints:

解法

递归解法

核心思想:求最大深度,其实就是求root的高度。求高度使用的是后序遍历,左右中

左右中,最后处理,才能递归把的结果,拿来给用。

为什么不使用前序遍历,中左右,来直接求深度呢?因为无法让下层节点利用上层节点来递归

递归实现:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        return self.getHeight(root)
    
    def getHeight(self, node: Optional[TreeNode]) -> int:
        # 终止条件
        if node is None:
            return 0

        # 单层核心逻辑
        # 以下四条语句,可以合并为最后一条语句
        # left_height = self.getHeight(node.left)
        # right_height = self.getHeight(node.right)
        # cur_height = max(left_height, right_height) + 1
        # return cur_height
        return 1 + max(self.getHeight(node.left), self.getHeight(node.right))