二叉树线索化与遍历线索二叉树

迈不过友情╰ 2022-07-15 02:26 316阅读 0赞

若某程序中所用二叉树经常遍历或查找节点在遍历所得线性序列中的后继和前驱,适用于线索链表存储结构即线索二叉树。

  1. #include <iostream>
  2. using namespace std;
  3. struct bithrnode//线索二叉树节点
  4. {
  5. char date;
  6. bithrnode *lchild,*rchild;
  7. int ltag,rtag;//左右标记,0为指针,1为线索
  8. };
  9. class bithrtree
  10. {
  11. private:
  12. bithrnode *root;
  13. bithrnode *pre;//pre始终指向刚刚访问(即中序遍历中输出过)过的节点
  14. bithrnode *q;//q指向当前访问的节点
  15. public:
  16. bithrtree()//这里引入根节点的作用是在建立变量bithrtree的时候就开始生成树
  17. //不必再引用create函数
  18. {
  19. create(root);
  20. };
  21. ~bithrtree();
  22. bithrnode *getroot()
  23. {
  24. return root;
  25. }
  26. void create(bithrnode *jj)//建立二叉树
  27. {
  28. char aa;
  29. cin>>aa;
  30. if(aa==' ') jj=NULL;
  31. else
  32. {
  33. jj=new bithrnode;
  34. jj->date=aa;
  35. create(jj->lchild);
  36. create(jj->rchild);
  37. }
  38. }
  39. void inorderthreading(bithrnode *aa)//中序遍历的二叉树线索化
  40. {
  41. //bithrtree *thrt=&aa(注释bithrtree aa)
  42. bithrnode *thrt=new bithrnode;//建立头节点
  43. thrt->ltag=0; thrt->rtag=1;
  44. if(aa) thrt->lchild=thrt;
  45. else
  46. {
  47. thrt->lchild=aa;
  48. pre=thrt;
  49. inthreading(aa);
  50. pre->rchild=thrt;//中序遍历后pre为最后一个叶子节点
  51. pre->rtag=0;
  52. thrt->rchild=pre;
  53. }
  54. }
  55. void inthreading(bithrnode *bb)
  56. {
  57. if(bb)
  58. {
  59. inthreading(bb->lchild);
  60. if(!bb->lchild) {bb->ltag=1;bb->lchild=pre;}
  61. if(!pre->rchild) {pre->rtag=1;pre->rchild=bb;}
  62. pre=bb;
  63. inthreading(bb->rchild);
  64. }
  65. }<pre name="code" class="cpp"> void inordertraverse(bithrnode *head)//中序遍历线索二叉树
  66. {
  67. bithrnode *pp=head->lchild;
  68. cout<<pp->date;
  69. while(pp!=head)
  70. {
  71. while(pp->lchild) pp=pp->lchild;
  72. cout<<pp->date;
  73. while(pp->rtag==1&&pp->rchild!=head)
  74. {
  75. pp=pp->rchild;
  76. cout<<pp->date;
  77. }
  78. pp=pp->rchild;//
  79. }
  80. }

}

发表评论

表情:
评论列表 (有 0 条评论,316人围观)

还没有评论,来说两句吧...

相关阅读

    相关 线索

    1,线索化二叉树基本介绍 线索化二叉树是对普通二叉树的扩展,对于普通二叉树而言,一个节点会包含一个数据域以及指向左右子节点的位置索引;但是对于叶子节点来讲,左右子节

    相关 线索

    二叉树是一种非线性结构,遍历二叉树几乎都是通过递归或者用栈辅助实现非递归的遍历。用二叉树作为存储结构时,取到一个节点,只 能获取节点的左孩子和右孩子,不能直接得到节点的任一遍历