【劍指offer】面試題39:二叉樹的深度

def TreeDepth1(root):
	if None == root:
		return 0
	if None == root.left and None == root.right:
		return 1
	leftDepth = 0; rightDepth = 0
	if root.left:
		leftDepth = TreeDepth(root.left)
	if root.right:
		rightDepth = TreeDepth(root.right)
	return max(leftDepth, rightDepth) + 1

簡潔點的

ef TreeDepth(root):
	if None == root:
		return 0
	return max(TreeDepth(root.left), TreeDepth(root.right)) + 1

代價是會進行無謂的遞歸
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章