c语言数据结构---线索二叉树

#include
#include

typedef struct node{
	struct node*lchild;
	struct node*rchild;
	int ltag;
	int rtag;//0后继1前驱 
	char data;
}Node,*Bit;
Node*pre;

Bit creat(){//先序创建 
char b;
int t;
scanf("%c",&b);
t=getchar();//吸收空格 
	if(b=='#')return NULL;
	else{
		Bit tree=(Bit)malloc(sizeof(Node));
		tree->data=b;
	printf("please input %c lefttree:",b);
        tree->lchild=creat();
		printf("please input %c righttree:",b); 
		tree->rchild=creat();
		return tree;
	}
}

void in(Node *tree){
	if(tree){
		in(tree->lchild);
		if(tree->lchild==NULL){
		tree->ltag=1;
		tree->lchild=pre;
	}
	if(pre&&pre->rchild==NULL){
		pre->rtag=1;
		pre->rchild=tree;
	}
	pre=tree;
	in(tree->rchild);
	}
	
} 
Node* next(Node*p){//求后继 
	Node*y=NULL;
	if(p->rtag)return p->rchild;
	else{
		if(!p->rchild)return NULL;
		y=p->rchild;
		if(y->rtag==0&&y->rchild==NULL)return y;
		while(y->ltag==0&&y->lchild!=NULL)y=y->lchild;
		return y;
	}
}
void print(Node*tree){
	Node*temp=tree;
	while(temp->lchild&&temp->ltag==0){
		temp=temp->lchild;
	}
	while(temp!=NULL){
		if(temp)printf("%c ",temp->data);
		temp=next(temp); 
	}
}
int main(){
	Bit tree;
	printf("please input root data:\n");
tree=creat();
printf("success creat a tree\n");
	in(tree);
	print(tree);
}

你可能感兴趣的:(数据结构,c语言,开发语言)