看看这个函数:
>>> def count_leaves(tree):
if is_leaf(tree):
return 1
else:
branch_counts = [count_leaves(b) for b in branches(tree)]
return sum(branch_counts)
>>> count_leaves(fib_tree(5))
8
函数在干嘛
这个函数回返回tree这个树的叶子节点的个数。
流程:
- if中的是base condition;
- else中的是递归的情况:数数树的每个分支的叶子节点个数,然后求和。
斐波那契树
>>> def fib_tree(n):
if n == 0 or n == 1:
return tree(n)
else:
left, right = fib_tree(n-2), fib_tree(n-1)
fib_n = label(left) + label(right)
return tree(fib_n, [left, right])
>>> fib_tree(5)
[5, [2, [1], [1, [0], [1]]], [3, [1, [0], [1]], [2, [1], [1, [0], [1]]]]]
fib_tree(5) 的结构如下图: