这是一个老技巧,仍然有效:
keep the back pointers in the call stack.
struct stacked_list{ struct stacked_list* prev; struct tree* tree; }; void printpath_helper(int data, struct stacked_list* path) { if (!path->prev) printf("%d PATH ", data); else printpath_helper(data, path->prev); printf("%d ", path->tree->data); } void printpath(struct stacked_list* path) { printpath_helper(path->tree->data, path); putchar('n'); } void preorder_helper(struct stacked_list* path) { if (path->tree) { printpath(path); struct stacked_list child = {path, path->tree->left}; preorder_helper(&child); child.tree = path->tree->right; preorder_helper(&child); } } void preorder(struct tree* tree) { struct stacked_list root = {NULL, tree}; preorder_helper(&root); }每次递归
preorder_helper都会创建一个参数struct,并将其地址传递给下一个递归,从而有效地创建了一个可链接的参数列表,该列表
printpath_helper可以向上移动以实际打印路径。由于您要从上至下打印路径
printpath_helper,因此还需要反向链接列表,因此最终会使该函数的递归深度加倍。如果您可以从头到尾进行打印,则
printpath_helper可能是一个简单的循环(或尾部递归)。



