线索二叉树(中序线索化,非递归遍历)

#include
#include


typedef char Type;
typedef struct Node{
	Type val;
	struct Node *lchild, *rchild;
	int ltag, rtag;//0-thread, 1-link
}Node, *Bptr;

Bptr pre; 
void InitialThread(Bptr *p){
	*p = (Node*)malloc(sizeof(Node));
	(*p)->lchild = NULL;
	(*p)->rchild = NULL;
}

void CreatB(Node **p){
	Type c;
	scanf("%c", &c);
	if(c == '#'){
		*p = NULL;
	}
	else{ 
		*p = (Bptr)malloc(sizeof(Node));
		if(!*p){
			exit(0);
		}
		(**p).val = c;
		(*p)->ltag = 1;
		(*p)->rtag = 1;
		CreatB(&((*p)->lchild));
		CreatB(&((*p)->rchild));
		}
}

void Thread(Node *p){
	if(p){
		Thread(p->lchild);
		if(p->lchild = NULL){
			p->ltag = 0;
			p->lchild = pre;
		}
		else if(pre->rchild = NULL){
			pre->rtag = 0;
			pre->rchild = p;
		}
		pre = p;
		printf("%c\n", pre->val);
		Thread(p->rchild);
	}
}

void O(Bptr p){
	Bptr temp = p->lchild;
	while(temp != NULL){
		while(temp->ltag == 1){
			temp = temp->lchild;
		}
		printf("%c", temp->val);
		while(temp->rtag == 0 && temp->rchild != NULL){
				temp = temp->rchild;
				printf("%c", temp->val);
		}
		temp = temp->rchild;
	}
}


int main(){
	Node *p;	
	CreatB(&p);
	InitialThread(&pre);
	Thread(p);
	O(p);
	return 0;
}

对前序创建的二叉树进行线索化,线索化通过递归实现。

void Thread(Node *p){
	if(p){
		Thread(p->lchild);
		if(p->lchild = NULL){
			p->ltag = 0;
			p->lchild = pre;
		}
		else if(pre->rchild = NULL){
			pre->rtag = 0;
			pre->rchild = p;
		}
		pre = p;
		printf("%c\n", pre->val);
		Thread(p->rchild);
	}
}

通过非递归的方式遍历线索二叉树。
不能选择递归的方式遍历线索二叉树。

void O(Bptr p){
	Bptr temp = p->lchild;
	while(temp != NULL){
		while(temp->ltag == 1){
			temp = temp->lchild;
		}
		printf("%c", temp->val);
		while(temp->rtag == 0 && temp->rchild != NULL){
				temp = temp->rchild;
				printf("%c", temp->val);
		}
		temp = temp->rchild;
	}
}

你可能感兴趣的:(软件工程)