網(wǎng)上的答案寫(xiě)法參差不齊,最大、最小深度寫(xiě)法不一。其實(shí)可以找到一個(gè)統(tǒng)一的寫(xiě)法解決最大、最小深度問(wèn)題。九章官方給出lintcode和leetcode的解法有點(diǎn)繁瑣(也可能是我菜,沒(méi)看出其中的奧妙),兩個(gè)else的內(nèi)容有點(diǎn)多余,。下面給出兩個(gè)問(wèn)題的統(tǒng)一寫(xiě)法。
主體思想三種情況分別討論:

主體思想鎮(zhèn)樓
當(dāng)root為空時(shí),返回深度0.
當(dāng)root.left為空時(shí),就在root.right繼續(xù)深度查找
當(dāng)root.right為空時(shí),就在root.left繼續(xù)深度查找
最后返回,root.left 和root.right的深度最大的值+1。
- 二叉樹(shù)最大深度:
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree.
@return: An integer
"""
def maxDepth(self, root):
if root is None:
return 0
if root.left == None:
return self.maxDepth(root.right) + 1
if root.right == None:
return self.maxDepth(root.left) + 1
return max(self.maxDepth(root.left), self.maxDepth(root.right))+1
- 二叉樹(shù)最小深度:
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param: root: The root of binary tree
@return: An integer
"""
def minDepth(self, root):
# write your code here
if root is None:
return 0
if root.left == None:
return self.minDepth(root.right) + 1
if root.right == None:
return self.minDepth(root.left) + 1
return min(self.minDepth(root.left),self.minDepth(root.right))+1