1. 程式人生 > >線索二叉樹實例(前序創建,中序遍歷)--2018.5.15

線索二叉樹實例(前序創建,中序遍歷)--2018.5.15

ID 中序遍歷 char turn 先序 AD 線索 lib data

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 
  4 typedef enum
  5 {
  6     Link,
  7     Tread
  8 }PointerTag;
  9 
 10 typedef char TElemType;
 11 
 12 typedef struct TreeNode
 13 {
 14     TElemType data;  //數據單元
 15 
 16     struct TreeNode *pLChild, *pRChild;  //左右孩子指針
 17     PointerTag LTag, RTag;  //
左右標誌 ==0:孩子指針;==1:前後驅 18 }TreeNode, Tree; 19 20 TreeNode *gPre = NULL; 21 22 /* 先序創建二叉樹 */ 23 void CreateTree(Tree **_t) 24 { 25 TElemType ch = -1; 26 27 scanf("%c", &ch); 28 29 if(ch == #) 30 *_t = NULL; 31 else 32 { 33 *_t = (Tree*)malloc(sizeof
(TreeNode)); 34 if(*_t == NULL) 35 return; 36 (*_t)->data = ch; 37 (*_t)->LTag = Link; 38 (*_t)->RTag = Link; 39 CreateTree(&((*_t)->pLChild)); 40 CreateTree(&((*_t)->pRChild)); 41 } 42 } 43 44 /* 遍歷二叉樹
*/ 45 int InOrderThraverse_Thr(Tree *_t) 46 { 47 Tree *p =NULL; 48 49 p = _t->pLChild; 50 while(p != _t) 51 { 52 while(p->LTag == Link) 53 p = p->pLChild; 54 55 printf("%c ", p->data); //對節點的操作 56 57 while((p->RTag == Tread) && (p->pRChild != _t)) 58 { 59 p = p->pRChild; 60 61 printf("%c ", p->data); 62 } 63 p = p->pRChild; 64 } 65 66 return 0; 67 } 68 69 void InOrderThreading(Tree *_p) 70 { 71 if(_p) 72 { 73 InOrderThreading(_p->pLChild); //左樹線索初始化 74 if(!_p->pLChild) //前驅線索 75 { 76 _p->LTag = Tread; 77 _p->pLChild = gPre; 78 } 79 if(!gPre->pRChild) //後繼線索 80 { 81 gPre->RTag = Tread; 82 gPre->pRChild = _p; 83 } 84 gPre = _p; 85 86 InOrderThreading(_p->pRChild); //右子樹線索初始化 87 } 88 } 89 90 /* 線索化二叉樹 */ 91 int InOrderThread_Head(Tree **_h, Tree *_t) 92 { 93 (*_h) = (TreeNode *)malloc(sizeof(TreeNode)); 94 if(*_h == NULL) 95 return -1; 96 97 (*_h)->pRChild = *_h; 98 (*_h)->RTag = Link; 99 100 if(!_t) 101 { 102 (*_h)->pLChild = *_h; 103 (*_h)->LTag = Link; 104 } 105 else 106 { 107 gPre = *_h; 108 (*_h)->LTag = Link; 109 (*_h)->pLChild = _t; 110 InOrderThreading(_t); 111 gPre->pRChild = *_h; 112 gPre->RTag = Tread; 113 (*_h)->pRChild = gPre; 114 } 115 116 return 0; 117 } 118 119 int main(void) 120 { 121 Tree *t=NULL, *temp=NULL; 122 123 printf("請輸入前序二叉樹的內容:\n"); 124 CreateTree(&t); 125 InOrderThread_Head(&temp, t); //加入頭結點,並線索化 126 printf("輸出中序二叉樹的內容:\n"); 127 InOrderThraverse_Thr(temp); 128 129 printf("\n"); 130 return 0; 131 }
mrrs@ubuntu:~/Desktop/DSC$ ./test
請輸入前序二叉樹的內容:
ABDG##H###CE#I##F##
輸出中序二叉樹的內容:
G D H B A E I C F

線索二叉樹實例(前序創建,中序遍歷)--2018.5.15