思路:递归,如果结点不为Null,那么最大深度加1。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root==None:
return 0
else:
return 1+max(self.maxDepth(root.left), self.maxDepth(root.right))
我自己写的版本稍慢一点点,
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def deep(root,max_depth):#求最大深度
if root==None:
return max_depth
return max(deep(root.left,max_depth+1),deep(root.right,max_depth+1))
return deep(root,0)