23-104. Maximum Depth of Binary Tree
Posted tbgatgb
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了23-104. 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.
代码实现:
1 # Definition for a binary tree node. 2 # class TreeNode(object): 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 class Solution(object): 9 def maxDepth(self, root): 10 """ 11 :type root: TreeNode 12 :rtype: int 13 """ 14 if not root: 15 return 0 16 17 return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
分析:
用递归的方法,分别深入左子树和右子树中去找,当左、右子树不存在时,抵达递归基,此时return 0.
以上是关于23-104. Maximum Depth of Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章
[Leetcode] Maximum Depth of Binary Tree
LC.104. Maximum Depth of Binary Tree
104. Maximum Depth of Binary Tree