[英]How do I find the maximum depth of a tree?
我有一個樹數據結構,定義如下:
class Tree(object):
def __init__(self, name='ROOT', children=None):
self.name = name
self.children = []
if children is not None:
for child in children:
self.add_child(child)
def __repr__(self):
return self.name
def add_child(self, node):
assert isinstance(node, Tree)
self.children.append(node)
我需要寫一個 function 來找到樹的深度。 這是我寫的 function (以 Tree 作為輸入,並返回 integer 值作為輸出),但它沒有給出正確的答案:
def depth(tree):
count = 1
if len(tree.children) > 0:
for child in tree.children:
count = count + 1
depth(child)
return count
我該如何糾正?
雖然您的depth(child)
確實進行了遞歸調用,但它對返回值(深度)沒有任何作用。 您似乎只是簡單地計算給定級別的節點並稱其為深度(實際上是寬度)。
您需要的是(偽代碼):
def maxDepth(node):
# No children means depth zero below.
if len(node.children) == 0:
return 0
# Otherwise get deepest child recursively.
deepestChild = 0
for each child in node.children:
childDepth = maxDepth(child)
if childDepth > deepestChild:
deepestChild = childDepth
# Depth of this node is one plus the deepest child.
return 1 + deepestChild
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.