栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

BST中节点的所有父节点?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

BST中节点的所有父节点?

这是一个老技巧,仍然有效:

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
可能是一个简单的循环(或尾部递归)。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/437213.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号