链接:
点击打开链接题目:
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
Example:
给定二叉树[3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回它的最大深度 3 。
解析:
- 如果根节点为空,则深度为0,返回0,递归的出口
- 如果根节点不为空,那么深度至少为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:
left = 1
right = 1
left = left + self.maxDepth(root.left)
right = right + self.maxDepth(root.right)
return max(left,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
"""
if root == None:
return 0
else:
return max(self.maxDepth(root.left),self.maxDepth(root.right)) + 1