class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Compute the "maxDepth" of a tree -- the number of nodes
# along the longest path from the root node down to the
# farthest leaf node
def maxDepth(node):
if node is None:
return 0 ;
else :
# Compute the depth of each subtree
lDepth = maxDepth(node.left) #HERE <--------------------
rDepth = maxDepth(node.right)
# Use the larger one
if (lDepth > rDepth):
return lDepth+1
else:
return rDepth+1
# Driver program to test above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print ("Height of tree is %d" %(maxDepth(root)))
所有这一切都是递归地进入maxDepth,直到不再有node.left或node.right,这如何返回深度
我已经在这里发表了评论来说明我困惑的地方。此代码如何知道要分配lDepth和rDepth的值
您可以这样想函数:
每一棵树都可以递归地被认为是一棵树,它的左右两侧各有两个子树。 因此,每个树的最大深度递归定义为左、右子树深度的最大值加上一
对于这种递归,可以选择两种等价的基本情况:
None
节点的深度为0在本例中,您选择了第一个基本情况
以下图为例:
以下是对先前答案的补充。我在您的原始代码中添加了一些打印输出,以便逐步演示递归的工作原理
相关问题 更多 >
编程相关推荐