前序遍历创建,前序打印。。。中序遍历添加索引,再循环打印。。。
typedef struct BiNode { char data; char ltag, rtag; struct BiNode *lchild, *rchild; }BiNode; void createTree(BiNode **root); void printTree(BiNode *root, int lever); void addThread(BiNode *root, BiNode **pre); void PTree(BiNode *root, const BiNode *pre); int main(int argc, char *argv[]) { BiNode *root = NULL; BiNode pre = {0, 't', 't', NULL, NULL}; BiNode *prePointer = ⪯ int lever = 1; createTree(&root); printTree(root, lever); pre.ltag = 't'; pre.lchild = root; addThread(root, &prePointer); pre.rtag = 't'; pre.rchild = prePointer; prePointer->rtag = 't'; prePointer->rchild = ⪯ PTree(root, &pre); return 0; } void createTree(BiNode **root) { char el; scanf("%c", &el); if(el == ' ') { *root = NULL; }else { *root = (BiNode *)malloc(sizeof(BiNode)); (*root)->data = el; (*root)->ltag = 'l'; (*root)->rtag = 'l'; createTree(&((*root)->lchild)); createTree(&((*root)->rchild)); } } void printTree(BiNode *root, int lever) { if(root) { printf("data: %c, lever: %d \n", root->data, lever); printTree(root->lchild, lever+1); printTree(root->rchild, lever+1); } } void addThread(BiNode *root, BiNode **pre) { if(root) { if(root->lchild) { addThread(root->lchild, pre); }else { root->ltag = 't'; root->lchild = (*pre); } if((*pre)->rchild == NULL) { (*pre)->rtag = 't'; (*pre)->rchild = root; } (*pre) = root; addThread(root->rchild, pre); } } void PTree(BiNode *root, const BiNode *pre) { BiNode *p = root; while(p->rchild != pre) { while(p->ltag == 'l') { p = p->lchild; } printf("%c ", p->data); while(p->rtag == 't' && p->rchild != pre) { p = p->rchild; printf("%c ", p->data); } p = p->rchild; } printf("%c \n", p->data); }
创建的时候输入需要类似:AB C \n
B C后面各有两个空格,代表其左子树和右子树都为空。。。。