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

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

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


Table of Contents

一、中文版

二、英文版

三、My answer

四、解题报告


一、中文版

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

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

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

示例:

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

   3

  / \

 9  20

   /  \

  15   7

返回它的最大深度 3 。

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


二、英文版

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,即是整棵树的高度。

相关文章
|
1月前
|
算法
LeetCode[题解] 1261. 在受污染的二叉树中查找元素
LeetCode[题解] 1261. 在受污染的二叉树中查找元素
16 1
|
1月前
力扣面试经典题之二叉树
力扣面试经典题之二叉树
16 0
|
2天前
[leetcode~dfs]1261. 在受污染的二叉树中查找元素
[leetcode~dfs]1261. 在受污染的二叉树中查找元素
[leetcode~dfs]1261. 在受污染的二叉树中查找元素
|
9天前
|
算法 DataX
二叉树(中)+Leetcode每日一题——“数据结构与算法”“剑指Offer55-I. 二叉树的深度”“100.相同的树”“965.单值二叉树”
二叉树(中)+Leetcode每日一题——“数据结构与算法”“剑指Offer55-I. 二叉树的深度”“100.相同的树”“965.单值二叉树”
|
11天前
|
算法
【力扣】94. 二叉树的中序遍历、144. 二叉树的前序遍历、145. 二叉树的后序遍历
【力扣】94. 二叉树的中序遍历、144. 二叉树的前序遍历、145. 二叉树的后序遍历
|
1月前
leetcode热题100.二叉树中的最大路径和
leetcode热题100.二叉树中的最大路径和
18 0
|
1月前
leetcode热题100. 二叉树的最近公共祖先
leetcode热题100. 二叉树的最近公共祖先
20 0
|
1月前
LeetCode-二叉树OJ题
LeetCode-二叉树OJ题
18 0
|
1月前
|
API
Leetcode-二叉树oj题
Leetcode-二叉树oj题
16 0
Leetcode-二叉树oj题
|
1月前
|
存储 Serverless 索引
二叉树的前序遍历 、二叉树的最大深度、平衡二叉树、二叉树遍历【LeetCode刷题日志】
二叉树的前序遍历 、二叉树的最大深度、平衡二叉树、二叉树遍历【LeetCode刷题日志】