以递归方式解析此树结构的所有级别的最佳方法是什么。这三个级别是第一个但是如何继续解析剩余数据?这来自于我无法完成的编纂测试。还有更多的问题,但这是我被卡住的地方。
tree = (5, (8, (12, None, None), (2, None, None)),(9, (7, (1, None, None), None), (4, (3, None, None), None)))
def recurse(T):
calc = 0
def do_calc(T, calc):
if T == ():
return calc
calc += 1
return do_calc(T[1:], calc)
return do_calc(T, calc)
print recurse(tree)
答案 0 :(得分:2)
通常,在递归使用binary trees时,您只需处理手头的节点并递归到子节点(如果有的话)。 “诀窍”是将孩子或子支柱视为树木本身。您还必须确定终止递归的边缘条件。
您当前的代码将使用初始节点(树的根),递增累加器calc
并递归调用do_calc
以获取元组的其余部分。这与递归孩子不同。由于根节点是3元组,recurse(tree)
将返回 3 。边缘条件是与空元组的比较。
您似乎想要计算树的节点:
def tree_count(tree):
# The edge condition: if a node is falsy (None, empty, what have you),
# then terminate the recursion
if not tree:
return 0
# Unpack the node, nicer to work with.
value, left, right = tree
# Count this node and recurse in to children.
return 1 + tree_count(left) + tree_count(right)
另一方面,如果最终目标是对树的值求和:
def tree_sum(tree):
# The edge condition
if not tree:
return 0
value, left, right = tree
# Sum this value and the values of children, if any
return value + tree_sum(left) + tree_sum(right)
如果您的实际树是k-ary tree或只是一棵树,每个节点有不同数量的子项:
def tree_sum(tree):
if not tree:
return 0
# This still makes the assumption that the value is the 1st item of
# a node tuple
value, children = tree[0], tree[1:]
# In python3:
#value, *children = tree
return value + sum(tree_sum(child) for child in children)
如上所述,代码假设节点是包含值的第一个元素的元组,就像提供的示例数据一样。如果没有看到实际数据,就不可能做得更好。如果您的节点实际上是(left, value, right)
元组左右,则相应地进行修改。
答案 1 :(得分:0)
看起来你想要树的深度。以下是递归的典型解决方案:
tree = (5, (8, (12, None, None), (2, None, None)),(9, (7, (1, None, None), None), (4, (3, None, None), None)))
def tree_depth(node):
if not isinstance(node, tuple):
return 1
else:
return max(tree_depth(subnode) for subnode in node) + 1
print tree_depth(tree)
输出 5 。
示例代码中使用了内置函数max和generator expression。