按照前序遍历的顺序建立一棵二叉树,并按中序遍历顺序输出,并和普通二叉树作比较
①头文件,枚举和二叉树结构体的定义
#include <stdio.h>
#include <stdlib.h>
#define TElemType char
typedef enum {
Link,//默认为0
Thread//默认为1
}PointerTag;
typedef struct BiThrNode
{
TElemType data;
struct BiThrNode *lchild,*rchild;
PointerTag Ltag,Rtag;
}BiThrNode,*BiThrTree;
BiThrTree pre=NULL;
②前序遍历初始化建立二叉树
BiThrTree CreateTree()
{
char ch;
BiThrTree T;
scanf("%c",&ch);
if(ch=='#') T=NULL;
else
{
T=(BiThrNode *)malloc(sizeof(BiThrNode));
T->data=ch;
T->lchild=CreateTree();
T->rchild=CreateTree();
}
return T;
}
③中序对二叉树进行线索化
void InThreading(BiThrTree p)
{
//如果当前结点存在
if (p)
{
InThreading(p->lchild);//递归当前结点的左子树,进行线索化
//如果当前结点没有左孩子,左标志位设为1,左指针域指向上一结点 pre
if (p->lchild==NULL)
{
p->Ltag=Thread;
p->lchild=pre;
}
//如果 pre 没有右孩子,右标志位设为 1,右指针域指向当前结点。
if (pre&&pre->rchild==NULL)
{
pre->Rtag=Thread;
pre->rchild=p;
}
pre=p;//pre指向当前结点
InThreading(p->rchild);//递归右子树进行线索化
}
}
④中序遍历线索二叉树
void InOrderThraverse_Thr(BiThrTree p)
{
while(p)
{
//一直找左孩子,最后一个为中序序列中排第一的
while(p->Ltag == Link){
p = p->lchild;
}
printf("%c ", p->data); //操作结点数据
//当结点右标志位为1时,直接找到其后继结点
while(p->Rtag == Thread && p->rchild !=NULL)
{
p = p->rchild;
printf("%c ", p->data);
}
//否则,按照中序遍历的规律,找其右子树中最左下的结点,也就是继续循环遍历
p = p->rchild;
}
}
⑤主函数的定义:
int main() {
printf("输入前序二叉树:\n");
BiThrTree t=CreateTree();
InThreading(t);
printf("输出中序序列:\n");
InOrderThraverse_Thr(t);
return 0;
}
⑥试验一下输入输出:
然后我们要是不建立线索二叉树的话进行一下输入输出:直接上递归
#include <stdio.h>
#include <stdlib.h>
typedef char ElementType;
typedef struct BiTNode
{
ElementType data;
struct BiTNode *Left,*Right;
}*BiTree;
BiTree CreateTree(){
char ch;
BiTree T;
scanf("%c",&ch);
if(ch=='#') T=NULL;
else
{
T=(BiTree)malloc(sizeof(BiTNode));
T->data=ch;
T->Left=CreateTree();
T->Right=CreateTree();
}
return T;
}
void InorderTraversal( BiTree BT );
int main()
{
BiTree BT;
printf("输入前序二叉树:\n");
BT=CreateTree();
printf("左根右 中序遍历:");
InorderTraversal(BT); printf("\n");
return 0;
}
void InorderTraversal( BiTree BT )
{
if(BT!=NULL)
{
InorderTraversal(BT->Left);
printf(" %c",BT->data);
InorderTraversal(BT->Right);
}
}
看一下运行结果: