题目:
求解二叉树的最大最小深度,即根节点(含)和叶子节点(含)之间的节点数最大,最少。其中最小深度求解复杂一丝儿~~
代码:
class Solution(object):
def maxDepth(self, root):
# 后序操作
def subDepth(root):
if not root:
return 0
left = subDepth(root.left)
right = subDepth(root.right)
return 1 + max(left, right)
return subDepth(root)
class Solution(object):
def minDepth(self, root):
# 仍是后序 比最大深度要复杂一丝
def subDepth(root):
if not root:
return 0
left = subDepth(root.left)
right = subDepth(root.right)
# left + right 是为了筛选其中一个子节点为空
# 其中至少一个为空,那么选择非空的那个即left+right
if not left or not right:
return 1 + left+right
# 不空,选择小的
else:
return 1 + min(left, right)
return subDepth(root)