二叉树的先序,中序,后序遍历 c语言

#include
#include

#define Data_Type char

typedef struct Node{
	Data_Type data;
	Node * lchird;
	Node * rchird;
}NODE, *PNODE;

PNODE create();
void preOrderTraverse(PNODE);
void inOrderTraverse(PNODE);
void postOrderTraverse(PNODE);
int main(void){

	PNODE pRoot = create();
	postOrderTraverse(pRoot);
	return 0;	
} 

PNODE create(){
	PNODE a = (PNODE)malloc(sizeof(PNODE));
	PNODE b = (PNODE)malloc(sizeof(PNODE));
	PNODE c = (PNODE)malloc(sizeof(PNODE));
	PNODE d = (PNODE)malloc(sizeof(PNODE));
	PNODE e = (PNODE)malloc(sizeof(PNODE));
	PNODE f = (PNODE)malloc(sizeof(PNODE));
	PNODE g = (PNODE)malloc(sizeof(PNODE));

	a->data = 'a';
	a->lchird = b;
	a->rchird = c;
	
	b->data = 'b';
	b->lchird = d;
	b->rchird = e;
	
	c->data = 'c';
	c->lchird = f;
	c->rchird = NULL;
	
	d->data = 'd';
	d->lchird = NULL;
	d->rchird = NULL;
	
	e->data = 'e';
	e->lchird = NULL;
	e->rchird = NULL;
	
	f->data = 'f';
	f->lchird = NULL;
	f->rchird = g;
	
	g->data = 'g';
	g->lchird = NULL;
	g->rchird = NULL;
	
	return a;
}

void preOrderTraverse(PNODE p){
	PNODE pRoot = p;
	printf("%c\n",pRoot->data);
	if(NULL!=pRoot->lchird){
		preOrderTraverse(pRoot->lchird);
	}
	if(NULL!=pRoot->rchird){
		preOrderTraverse(pRoot->rchird);
	}
}

void inOrderTraverse(PNODE ps){	
	PNODE pRoot = p;
	if(NULL!=pRoot->lchird){
		inOrderTraverse(pRoot->lchird);
	}
	printf("%c\n",pRoot->data);
	if(NULL!=pRoot->rchird){
		inOrderTraverse(pRoot->rchird);
	}
}

void postOrderTraverse(PNODE p){
	PNODE pRoot = p;
	if(NULL!=pRoot->lchird){
		postOrderTraverse(pRoot->lchird);
	}
	if(NULL!=pRoot->rchird){
		postOrderTraverse(pRoot->rchird);
	}
	printf("%c\n",pRoot->data);
}

你可能感兴趣的:(数据结构)