二叉树中序线索化及遍历
#include<stdio.h>
#include<stdlib.h>
typedef int elemtype;
typedef struct TNode{
elemtype data;
TNode *rchild,*lchild,*parent;
int rtag,ltag; //0为孩子结点,1为线索
}TNode,*Bitree;
void inThread(Bitree &bt,Bitree &pre);
void createT(Bitree &bt,Bitree pre){ // 前序构建二叉树
int c;
scanf("%d",&c);
if(c!=-1){
bt=(TNode*)malloc(sizeof(TNode));
bt->data=c;
bt->ltag=0;
bt->rtag=0;
bt->parent=pre;
createT(bt->lchild,bt);
createT(bt->rchild,bt);
}else{
bt=NULL;
}
}
void createInThread(Bitree &bt){ //中序线索二叉树
Bitree pre=NULL;
if(bt){
inThread(bt,pre);
pre->rchild=NULL;
pre->rtag=1;
}
}
void inThread(Bitree &bt,Bitree &pre){
if(bt!=NULL){
inThread(bt->lchild,pre);
if(bt->lchild==NULL){
bt->lchild=pre;
bt->ltag=1;
}
if(pre&&pre->rchild==NULL){
pre->rchild=bt;
pre->rtag=1;
}
pre=bt;
inThread(bt->rchild,pre);
}
}
Bitree First(Bitree bt){ //中序第一个节点
while(bt->ltag==0)
bt=bt->lchild;
return bt;
}
Bitree Next(Bitree bt){ //bt在中序下的后继节点
if(bt->rtag==0)
return First(bt->rchild);
else
return bt->rchild;
}
void Inorder(Bitree bt){ //中序遍历线索二叉树
Bitree p;
for(p=First(bt);p;p=Next(p)){
printf("%d ",p->data);
}putchar(10);
}
void printT(Bitree bt){ //前序遍历二叉树
if(bt){
printf("%d ",bt->data);
printT(bt->lchild);
printT(bt->rchild);
}
}
int main(){
Bitree bt;
createT(bt,NULL);
printT(bt);
putchar(10);
createInThread(bt);
Inorder(bt);
int a=1,b=3;
Bitree p;
for(p=First(bt);p;p=Next(p)){
if(p->data>a&&p->data<b)
printf("%d ",p->data);
}
return 0;
}
输入:
5 3 2 1 -1 -1 -1 4 -1 -1 7 6 -1 -1 -1 5 -1 -1
输出:
5 3 2 1 4 7 6
1 2 3 4 5 6 7
2