关于线索二叉树建立和遍历
#include <stdio.h>
#include <stdlib.h>
typedef struct ThreadNode {
char data;
struct ThreadNode *lchild, *rchild;
int ltag, rtag; //0为孩子,1为线索
}ThreadNode,*ThreadTree;
ThreadTree PreCreatebiTree(ThreadTree p,bool isroot) { //先序创建二叉树
char ch;
if (isroot)
printf("root: ");
fflush(stdin);
scanf("%c", &ch);
fflush(stdin); //清空缓存区,确保不影响后面的数据读取(例如在读完一个字符串后紧接着又要读取一个字符,此时应该先执行fflush(stdin))
getchar(); //etchar()去掉回车
if (ch != '#') {
isroot = false;
p = (ThreadNode*)malloc(sizeof(ThreadNode));
p->data = ch;
p->lchild = NULL;
p->rchild = NULL;
p->ltag = 0;
p->rtag = 0;
printf("%c's left child is: ", p->data);
p->lchild=PreCreatebiTree(p->lchild,isroot);
printf("%c's right child is: ", p->data);
p->rchild=PreCreatebiTree(p->rchild,isroot);
}
return p;
}
void PrebiTree(ThreadTree T) { //先序遍历二叉树
if (T != NULL) {
printf("%c %d %d\n", T->data, T->ltag, T->rtag);
PrebiTree(T->lchild);
PrebiTree(T->rchild);
}
}
void InThread(ThreadNode *p, ThreadNode *&pre) { //中序线索递归 p引用不引用一样
if (p != NULL) {
InThread(p->lchild, pre);
if (p->lchild == NULL) {
p->lchild = pre;
p->ltag = 1;
}
if (pre!=NULL&&pre->rchild == NULL) {
pre->rchild = p;
pre->rtag = 1;
}
pre = p;
InThread(p->rchild, pre);
}
}
void CreateInThread(ThreadTree p) { //二叉树中序线索化
ThreadNode *pre = NULL;
if (p != NULL) {
InThread(p, pre);
pre->rchild = NULL;
pre->rtag = 1;
}
}
ThreadNode *FirstNode(ThreadNode *p) { //当前根结点点中序序列下第一个结点
if (p == NULL) {
return NULL;
}
while (p->ltag == 0)
p = p->lchild;
return p;
}
ThreadNode *LastNode(ThreadNode *p) { //当前根结点点中序序列下最后一个结点
if (p == NULL) {
return NULL;
}
while (p->rtag == 0)
p = p->rchild;
return p;
}
ThreadNode *NextNode(ThreadNode *p) { //当前结点后继
if (p == NULL) {
return NULL;
}
if (p->rtag == 0)
return FirstNode(p->rchild);
return p->rchild;
}
ThreadNode *PreNode(ThreadNode *p) { //当前结点前驱
if (p == NULL) {
return NULL;
}
if (p->ltag == 0)
return LastNode(p->lchild);
return p->lchild;
}
void InOrder(ThreadTree T) { //中序遍历
ThreadNode *p=NULL;
for (p = FirstNode(T); p != NULL; p = NextNode(p))
printf("%c %d %d\n", p->data, p->ltag, p->rtag);
} //
void RevInOrder(ThreadTree T) { //逆向中序遍历
ThreadNode *p = NULL;
for(p=LastNode(T);p!=NULL;p=PreNode(p))
printf("%c %d %d\n", p->data, p->ltag, p->rtag);
}
int main() {
ThreadTree T=NULL;
T=PreCreatebiTree(T,1);
PrebiTree(T);
printf("\nbiTree create done\n");
CreateInThread(T);
printf("InOrder\n");
InOrder(T);
printf("RevInOrder:\n");
RevInOrder(T);
getchar();
return 0;
}
Don't aim for success if you really want it.Just stick to what you love and believe in.And it will come naturally.