LeetCode 104. 二叉树的最大深度 Maximum Depth of Binary Tree

106 阅读1分钟

Table of Contents

一、中文版

二、英文版

三、My answer

四、解题报告


一、中文版

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

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

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

示例:
给定二叉树 [3,9,20,null,null,15,7],

    3
/ \
9  20
/  \
15   7
返回它的最大深度 3 。

来源:力扣(LeetCode)
链接:leetcode-cn.com/problems/ma…
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二、英文版

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
/ \
9  20
/  \
15   7
return its depth = 3.

三、My answer

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
# version 1:
class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if not root:
            return 0
        left = self.maxDepth(root.left)
        right = self.maxDepth(root.right)
        return max(left,right) + 1

四、解题报告

1、如果根节点为空,返回值是0,这也是递归出口。

2、求出左子树的高度和右子树的高度,加上根节点的1,即是整棵树的高度。