C语言实现先序、中序、后序遍历一颗二叉树
#include<stdio.h>
#include<malloc.h>
#define null 0
int counter=0;
typedef struct btreenode
{
int data;
struct btreenode *lchild;
struct btreenode *rchild;
}bnode; bnode *p;
bnode *creat(int x, bnode *lbt, bnode *rbt){
bnode *p;
p = (bnode*)malloc(sizeof(bnode));
p -> data = x;
p -> lchild = lbt;
p -> rchild = rbt;
return(p);
}
bnode *ins_lchild(bnode *p, int x){
bnode *q;
if(p == null)
printf("illegal insert");
else{
q = (bnode*)malloc(sizeof(bnode));
q -> data = x;
q -> lchild = null;
q -> rchild = null;
if(p -> lchild != null)
q -> rchild = p -> lchild;
p -> lchild = q;
}
}
bnode *ins_rchild(bnode *p, int x){
bnode *q;
if(p == null)
printf("illegal insert");
else{
q=(bnode*)malloc(sizeof(bnode));
q -> data = x;
q -> lchild = null;
q -> rchild = null;
if(p -> rchild != null)
q -> lchild = p -> rchild;
p -> rchild = q;
}
}
void prorder(bnode *p){
if(p == null)
return;
printf("%d\t%u\t%d\t%u\t%u\n", ++counter, p, p -> data, p -> lchild, p -> rchild);
if(p -> lchild != null)
prorder(p -> lchild);
if(p -> rchild != null)
prorder(p -> rchild);
}
void preorder(bnode *p){
if(p == NULL)
return;
printf("%d", p -> data);
preorder(p -> lchild);
preorder(p -> rchild);
}
void inorder(bnode *p){
if(p == NULL)
return;
inorder(p -> lchild);
printf("%d", p -> data);
inorder(p -> rchild);
}
void postorder(bnode *p){
if(p == NULL)
return;
postorder(p -> lchild);
postorder(p -> rchild);
printf("%d", p -> data);
}
void main() {
bnode *bt,*p,*q;
int x;
printf("Input root:");
scanf("%d",&x);
p=creat(x,null,null); bt=p;
scanf("%d",&x);
while(x!=-1){
p = bt;
q = p;
while(x!=p->data&&q!=null){
p=q;
if(x<p->data)
q=p->lchild;
else
q=p->rchild;
}
if(x==p->data){
printf("The data is exit.");
return;
}
else
if(x<p->data)
ins_lchild(p,x);
else
ins_rchild(p,x);
scanf("%d",&x);
}
p=bt;
printf("structure of the binary tree:\n");
printf("number\taddress\tdata\tlchild\trchild\n");
prorder(p);
printf("preorder:");
preorder(p);
printf("\n");
printf("inorder:");
inorder(p);
printf("\n");
printf("postorder:");
postorder(p);
printf("\n");
}