用C语言写出线索二叉树的建立与遍历代码
时间: 2023-06-03 18:07:19 浏览: 133
好的,以下是用C语言写出线索二叉树的建立与遍历代码:
/*定义线索二叉树的结点结构体*/
typedef struct ThreadNode {
int data; //结点数据
int ltag, rtag; //左、右树是否线索化标志
struct ThreadNode *lchild, *rchild; //左、右孩子指针
}ThreadNode, *ThreadTree;
/*线索化中序遍历函数*/
void InThread(ThreadTree T, ThreadTree &pre) {
if (T != NULL) {
InThread(T->lchild, pre); //递归生成左子树线索
if (T->lchild == NULL) { //左孩子为空,建立前驱线索
T->lchild = pre; //前驱线索指向pre
T->ltag = 1; //左线索标志设置为1
}
if (pre != NULL && pre->rchild == NULL) { //右孩子为空,建立后继线索
pre->rchild = T; //后继线索指向T
pre->rtag = 1; //右线索标志设置为1
}
pre = T; //pre指向当前结点
InThread(T->rchild, pre); //递归生成右子树线索
}
}
/*构造线索二叉树函数*/
void CreateInThread(ThreadTree T) {
ThreadTree pre = NULL; //定义pre结点表示中序遍历中T的前驱结点
if (T != NULL) {
InThread(T, pre); //中序遍历线索化二叉树
pre->rchild = NULL; //处理遍历的最后一个结点
pre->rtag = 1; //右线索标志设置为1
}
}
/*遍历线索二叉树函数*/
void InOrderThread(ThreadTree T) {
ThreadTree p = T;
while (p != NULL) {
while (p->ltag == 0) { //左线索为0,则一直遍历左子树
p = p->lchild;
}
printf("%d ", p->data); //输出结点数据
while (p->rtag == 1 && p->rchild != NULL) { //右线索为1,则一直遍历右子树
p = p->rchild;
printf("%d ", p->data); //输出结点数据
}
p = p->rchild; //p指向直接后继
}
}
/*测试函数*/
int main() {
//构造线索二叉树
ThreadTree T = (ThreadTree)malloc(sizeof(ThreadNode));
T->data = 1;
T->ltag = 0;
T->rtag = 0;
T->lchild = (ThreadTree)malloc(sizeof(ThreadNode));
T->lchild->data = 2;
T->lchild->ltag = 0;
T->lchild->rtag = 0;
T->lchild->lchild = NULL;
T->lchild->rchild = (ThreadTree)malloc(sizeof(ThreadNode));
T->lchild->rchild->data = 4;
T->lchild->rchild->ltag = 0;
T->lchild->rchild->rtag = 0;
T->lchild->rchild->lchild = NULL;
T->lchild->rchild->rchild = NULL;
T->rchild = (ThreadTree)malloc(sizeof(ThreadNode));
T->rchild->data = 3;
T->rchild->ltag = 0;
T->rchild->rtag = 0;
T->rchild->lchild = (ThreadTree)malloc(sizeof(ThreadNode));
T->rchild->lchild->data = 5;
T->rchild->lchild->ltag = 0;
T->rchild->lchild->rtag = 0;
T->rchild->lchild->lchild = NULL;
T->rchild->lchild->rchild = NULL;
T->rchild->rchild = (ThreadTree)malloc(sizeof(ThreadNode));
T->rchild->rchild->data = 6;
T->rchild->rchild->ltag = 0;
T->rchild->rchild->rtag = 0;
T->rchild->rchild->lchild = NULL;
T->rchild->rchild->rchild = NULL;
CreateInThread(T); //生成线索二叉树
printf("中序遍历线索二叉树:");
InOrderThread(T); //遍历线索二叉树
printf("\n");
return 0;
}
阅读全文