LeetCode基础算法

mac2026-08-30  9

二叉树的最大深度

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

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

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

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

3 / \ 9 20 / \ 15 7

返回它的最大深度 3 。


python代码如下: 1,可能较容易理解的版本

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

i,j分别记录左右子树的深度,一旦遍历至叶子节点开始返回,最后比较左右子树,返回最大深度


更简洁的版本:

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

中间变量完全可以抛弃,直接递归即可.

最新回复(0)