/*win-tc*/
#include"stdio.h"
#include"stdlib.h"
#include"conio.h"
#include"ctype.h"
#define MAXSIZE 100
#define NULL 0
typedef struct tree /*定义树结点结构*/
{
struct tree* lchild;
struct tree* rchild;
int data;
}treenode,*bintree;
bintree insert_node(bintree root,int node) /*向二叉树中插入新结点*/
{
bintree newnode;
bintree currentnode;
bintree parentnode;
newnode=(bintree)malloc(sizeof(treenode));
newnode->data=node;
newnode->rchild=NULL;
newnode->lchild=NULL;
if(root==NULL) /*空树,新结点成为根结点*/
return newnode;
else /*插入孩子结点*/
{
currentnode=root;
while(currentnode!=NULL)
{
parentnode=currentnode; /*判断插入数据与当前结点的大小*/
if(currentnode->data>node) /*如果数据小则将光标移到结点的左指针*/
currentnode=currentnode->lchild;
else /*如果数据大则将光标移到结点的右指针*/
currentnode=currentnode->rchild;
}
if(parentnode->data>node) /*插入数据小则做为左孩子*/
parentnode->lchild=newnode;
else /*插入数据大则做为右孩子*/
parentnode->rchild=newnode;
}
return root;
}
bintree create_tree(int data[],int len) /*利用插入算法创建二叉树*/
{
bintree root;
int i;
root=NULL;
for(i=0;i<len;i++)
root=insert_node(root,data[i]) ;
return root;
}
void preorder(bintree root) /*先序遍历二叉树的递归算法*/
{
if(root!=NULL)
{
printf("%d ",root->data);
preorder(root->lchild);
preorder(root->rchild);
}
}
void inorder(bintree root) /*中序遍历二叉树的递归算法*/
{
if(root!=NULL)
{
preorder(root->lchild);
printf("%d ",root->data);
preorder(root->rchild);
}
}
void postorder(bintree root) /*后序遍历二叉树的递归算法*/
{
if(root!=NULL)
{
preorder(root->lchild);
preorder(root->rchild);
printf("%d ",root->data);
}
}
void main()
{
bintree root=NULL;
int i,index;
int value;
int nodelist[MAXSIZE];
clrscr();
printf("please input the elenents of binary tree(Exit for 0):/n/n");
index=0;
scanf("%d",&value);
while(value!=0) /*输入结点*/
{
nodelist[index]=value;
index++;
scanf("%d",&value);
}
root=create_tree(nodelist,index);
printf("/n/nthe preorder reaversal result is: [ ");
preorder(root);
printf("]/n/n");
printf("/n/nthe inorder reaversal result is: [ ");
inorder(root);
printf("]/n/n");
printf("/n/nthe postorder reaversal result is: [ ");
postorder(root);
printf("]/n/n");
getch();
}
结果如下: