網上的答案寫法參差不齊,最大、最小深度寫法不一。其實可以找到一個統一的寫法解決最大、最小深度問題。九章官方給出lintcode和leetcode的解法有點繁瑣(也可能是我菜,沒看出其中的奧妙),兩個else的內容有點多余,。下面給出兩個問題的統一寫法。
主體思想三種情況分別討論:
主體思想鎮樓
當root為空時,返回深度0.
當root.left為空時,就在root.right繼續深度查找
當root.right為空時,就在root.left繼續深度查找
最后返回,root.left 和root.right的深度最大的值+1。
- 二叉樹最大深度:
"""
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
- 二叉樹最小深度:
"""
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