#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_OP 20;
typedef struct Node{
int val;
struct Node* lchild,*rchild;
}Node;
Node* getNewNode(int val){
Node* node=(Node*)malloc(sizeof(Node));
node->val=val;
node->rchild=node->lchild=NULL;
return node;
}
void clearNode(Node* root){
if(root==NULL){
return;
}
clearNode(root->lchild);//
clearNode(root->rchild);//
free(root);
return;
}
Node* insert(Node* root,int val){
if(root==NULL){
root=getNewNode(val);
return root;
}
if(root->val==val)return root;
if(val<root->val) {
root->lchild=insert(root->lchild,val);
}
if(val>root->val){
root->rchild=insert(root->rchild,val);
}
return root;
}
void inorder(Node* root){
if(root==NULL)return;
inorder(root->lchild);
printf("%d->",root->val);
inorder(root->rchild);
return;
}
int main() {
srand(time(0));
Node* root=NULL;
for(int i=0;i<15;i++){
int val=rand()%100;
root=insert(root,val);
}
inorder(root);
printf("\n");
clearNode(root);
return 0;
}
假设输出树结构为:
tree(15)=58(36(3(Null,20(8,21(Null,23(22,Null)))),53(38,Null)),88(79(Null,87),95(94,Null)))
用树结构表示为: