def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
最小深度,注意其中一个孩子不为None,另一个孩子为None的情况
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
if not root.left and root.right:
return self.minDepth(root.right) + 1
if not root.right and root.left:
return self.minDepth(root.left) + 1
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
最小深度bfs解法,判断当前结点是否为叶子结点。
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
queue = [root]
level = 1
while queue:
n = len(queue)
for i in range(n):
cur = queue.pop(0)
if not cur.left and not cur.right:
return level
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
level += 1