#include<stdlib.h>
#include<stdio.h>
#include<time.h>
typedef struct Node{ //结构定义
int key;
struct Node *lchild,*rchild;
}Node;
Node *getNewNode(int key){ //建立结点
Node *p=(Node *)malloc(sizeof(Node));
p->key=key;
p->lchild=p->rchild=NULL;
return p;
}
void clear(Node *root){ //二叉树的递归清空
if(root==NULL) return ;
clear(root->lchild);
clear(root->rchild);
free(root);
return ;
}
Node *insert(Node *root,int key){ //二叉树的递归插入
if(root==NULL) return getNewNode(key);
if(rand()%2) root->lchild=insert(root->lchild,key);
else root->rchild=insert(root->rchild,key);
return root;
}
void pre_order(Node *root){ //前序遍历
if(root==NULL) return ;
printf("%d ",root->key);
pre_order(root->lchild);
pre_order(root->rchild);
return ;
}
void in_order(Node *root){ //中序遍历
if(root==NULL) return ;
in_order(root->lchild);
printf("%d ",root->key);
in_order(root->rchild);
return ;
}
void post_order(Node *root){ //后序遍历
if(root==NULL) return ;
post_order(root->lchild);
post_order(root->rchild);
printf("%d ",root->key);
return ;
}
const int N=10;
int main(){
srand(time(0));
Node *root=NULL;
for(int i=0;i<N;i++){
root=insert(root,rand()%100);
}
pre_order(root); printf("\n");
in_order(root); printf("\n");
post_order(root); printf("\n");
clear(root);
return 0;
}