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 101 102 103 104
|
#include <stdio.h> #include <stdlib.h> #include <sys/wait.h>
typedef struct TreeNode { char data; struct TreeNode* lchild; struct TreeNode* rchild; struct TreeNode* parent; int ltag; int rtag; }TreeNode;
void createTree(TreeNode** T, char* data, int* index, TreeNode* parent) { char ch; ch = data[*index]; *index += 1; if (ch == '#') { *T = NULL; } else { *T = (TreeNode*)malloc(sizeof(TreeNode)); (*T) -> data = ch; (*T) -> ltag = 0; (*T) -> rtag = 0; (*T) -> parent = parent; createTree(&((*T)->lchild), data, index, *T); createTree(&((*T)->rchild), data, index, *T); } }
void postThreadTree(TreeNode* T, TreeNode** pre) { if (T) { postThreadTree(T -> lchild, pre); postThreadTree(T -> rchild, pre); if (T -> lchild == NULL) { T -> ltag = 1; T -> lchild = *pre; } if (*pre != NULL && (*pre) -> rchild == NULL) { (*pre) -> rtag = 1; (*pre) -> rchild = T; } *pre = T; } }
TreeNode* getFirst(TreeNode* T) { while (T -> ltag == 0) T = T -> lchild; if (T -> rtag == 0) { return getFirst(T -> rchild); } return T; }
TreeNode* getNext(TreeNode* node) { if (node -> rtag == 1) return node -> rchild; else { if (node -> parent == NULL) { return NULL; } else if (node -> parent -> rchild == node) { return node -> parent; } else { if (node -> parent -> ltag == 0) { return getFirst(node -> parent -> rchild); } else { return node -> parent; } } } }
int main(int argc, char* argv[]) { TreeNode* T; TreeNode* pre = NULL; int index = 0; createTree(&T, argv[1], &index, NULL); postThreadTree(T, &pre); for (TreeNode* node = getFirst(T); node != NULL; node = getNext(node)) { printf("%c ", node -> data); } printf("\n"); return 0; }
|