定义:从根节点到最近叶子结点的最短路径上的节点个数
实现:
class TreeNode(object): def __init__(self, item): self.item = item self.left = None self.right = None def create_tree(): n1 = TreeNode(1) n2 = TreeNode(2) n3 = TreeNode(3) n4 = TreeNode(4) n5 = TreeNode(5) n6 = TreeNode(6) n7 = TreeNode(7) n1.left = n2 n1.right = n3 n2.left = n4 n2.right = n5 n4.left = n6 n4.right = n7 return n1 def min_deep(head): if not head: # 空树返回0;当前没有数据,迭代停止条件 return 0 if not head.left: # 没有左孩子,计算右孩子 return min_deep(head.right) + 1 if not head.right: # 没有右孩子,计算左孩子 return min_deep(head.left) + 1 # 左右孩子完整,取最小的 return min(min_deep(head.left), min_deep(head.right)) + 1 if __name__ == '__main__': print(min_deep(create_tree()))
结果返回:2