如何编写递归函数的方法定义

How to write the method definition for a recursive function?

本文关键字:方法 定义 递归函数 何编写      更新时间:2023-10-16

Printer_Helper是一个递归函数,用于打印链表的内容。

struct Node
{
    string data;
    Node *next;
}
void List::print() 
{
    Print_Helper(head);
}

如何编写递归函数的方法定义?

基本上递归是这样工作的:

  • 你有一个问题(打印一个节点)
  • 部分问题是为当前问题的一小部分解决相同的问题(打印子节点)
  • 在某些情况下,没有更小的问题存在,你可以停止解决(没有更多的子节点)

在这种情况下,它的工作方式是:

print content of current node
if there are any child nodes:
    for each child node:
        call this function with the child node