您的位置:首页 > 编程语言 > C语言/C++

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

2015-08-10 13:29 399 查看
#include<Stdio.h>
#include<malloc.h>

#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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息