1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
| #include <stdio.h> #include <stdlib.h>
enum { Link, Thread } Tag;
typedef struct TNode { char data; struct TNode *lchild; struct TNode *rchild; unsigned char ltag; unsigned char rtag; } TNode;
TNode *pre = NULL;
TNode *createNode(char data, TNode *lchild, TNode *rchild) { TNode *node = (TNode *)malloc(sizeof(TNode)); node->data = data; node->lchild = lchild; node->rchild = rchild; node->ltag = Link; node->rtag = Link; return node; }
void inThreading(TNode *tree) { if (tree) { inThreading(tree->lchild); if (!tree->lchild) { tree->ltag = Thread; tree->lchild = pre; } if (!pre->rchild) { pre->rtag = Thread; pre->rchild = tree; } pre = tree; inThreading(tree->rchild); } }
void InOrderThreading(TNode *tree, TNode *head) { head->data = 0; head->ltag = Link; head->lchild = tree; if (!tree) { return; } pre = tree; inThreading(tree); pre->rchild = head; pre->rtag = Thread; head->rchild = pre; }
void InOrderTraverse(TNode *head) { TNode *n = head->lchild; while (n != head) { while (n->ltag == Link) { n = n->lchild; } printf("%c ", n->data);
while (n->rtag == Thread && n->rchild != head) { n = n->rchild; printf("%c ", n->data); } n = n->rchild; } }
int main(int argc, char const *argv[]) { TNode *tree = createNode('1', createNode('2', createNode('4', NULL, NULL), createNode('5', NULL, NULL)), createNode('3', createNode('6', NULL, NULL), createNode('7', NULL, NULL))); TNode head; InOrderThreading(tree, &head); InOrderTraverse(&head);
return 0; }
|