使用递归计算二叉树的叶子:(递归函数)+(递归函数)的最终return语句

Counting the leaves of a binary tree using recursion: the final return statement of (recursive function)+(recursive function)

最近在学习二叉树,看了看叶子数的代码

这是计算树叶数的递归函数:

def __count_leaves_recursive(self, node):

    if node == None:
        return 0

    elif node.left == None and node.right == None:
        return 1

    else:
        return self.__count_leaves_recursive(node.left) + self.__count_leaves_recursive(node.right)

在学习递归如何处理树时,Python Tutor visualisation tool 非常宝贵。但是,它并没有帮助我想象最终的 return 声明。当一个递归函数被添加到同一行中的另一个递归函数时,我很难想象发生了什么。

程序到达递归函数时是否与其他任何时候一样?在那里,程序只是简单地记录它进入函数的位置,以便 return 到函数完成后的同一位置?

Is it simply the same as any other time the program reaches a recursive function?

是的,您可以像这样想象那行代码:

a = self.__count_leaves_recursive(node.left)
b = self.__count_leaves_recursive(node.right)
return a + b

因此第一个递归调用必须在第二个调用启动之前完全完成。当第二个递归调用也完成其工作时,两个返回值相加,并将该值返回给调用者。