leetcode解题-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.

分析

深度优先遍历可解,时间O(n),空间平均O(logn)

代码

Python

1
2
3
4
5
6
7
8
9
10
11
class (object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""

if not root:
return 0
d1 = self.maxDepth(root.left)
d2 = self.maxDepth(root.right)
return max(d1, d2) + 1