#include <stdio.h>
#include <stdlib.h>
#include "tree.h"
#include "lk.h"
/*typedef struct tree{
int data;
struct tree *lchild;
struct tree *rchild;
}TREE;
*/
TREE *create1(int i,int n )
{
TREE *root=(TREE *)malloc(sizeof(TREE));
if(root==NULL)
return NULL;
root->data=i;
if(2*i<=n)
{
root->lchild=create1(2*i,n);
}
else
root->lchild= NULL;
if(2*i+1<=n)
{
root->rchild=create1(2*i+1,n);
}
else
root->rchild= NULL;
return root;
}
void xian(TREE *root)
{
if(root==NULL)
return ;
printf("%d ",root->data);
xian(root->lchild);
xian(root->rchild);
}
void zhong(TREE *root)
{
if(root==NULL)
return ;
zhong(root->lchild);
printf("%d ",root->data);
zhong(root->rchild);
}
void hou(TREE *root)
{
if(root==NULL)
return ;
hou(root->lchild);
hou(root->rchild);
printf("%d ",root->data);
}
//cengci
void fcengci(TREE *root)
{
if(NULL==root)
return ;
LIST *list=create();
insert(list,root);
while(empty(list)!=1)
{
TREE *root=del(list);
printf("%d ",root->data);
if(root->lchild!=NULL)
{
insert(list,root->lchild);
}
if(root->rchild!=NULL)
{
insert(list,root->rchild);
}
}
return ;
}
int main(int argc, char *argv[])
{
TREE *p=create1(1,12);
printf("xian:");
xian(p);
putchar('\n');
printf("zhong:");
zhong(p);
putchar('\n');
printf("hou:");
hou(p);
putchar('\n');
fcengci(p);
putchar('\n');
return 0;
}
lk.h里面是链队的操作
#ifndef lkl
#define lkl
#include "tree.h"
typedef TREE *data_t;
typedef struct node{
data_t data;
struct node *next;
}NODE;//tou jie dian
typedef struct list{
struct node *front;
struct node *rear;
}LIST;
LIST *create();
int empty(LIST *list);
int lenth(LIST *list);
int insert(LIST *list,data_t data);
data_t del(LIST *list);
void dayin(LIST *list);
#endif
tree.h如下
#ifndef tree_
#define tree_
typedef struct tree{
int data;
struct tree *lchild;
struct tree *rchild;
}TREE;
TREE *create1(int i,int n);
void xian(TREE *root);
void zhong(TREE *root);
#endif
链队的操作就不放了