题目描述:
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.
我的思路:
递归调用左右树,最后加一,取最大。
我的代码:
def maxDepth(self, root: TreeNode) -> int:
if root == None:
return 0
a = self.maxDepth(root.left) + 1
b = self.maxDepth(root.right) + 1
return max(a, b)
Discuss:
也可以使用层次遍历,统计层数。
def maxDepth(self, root):
if not root:
return 0
tstack,h = [root],0
#count number of levels
while tstack:
nextlevel = []
while tstack:
top = tstack.pop()
if top.left:
nextlevel.append(top.left)
if top.right:
nextlevel.append(top.right)
tstack = nextlevel
h+=1
return h