#include<stdio.h>
#include<stdlib.h>
#include<time.h>
typedef struct Node {
int data;
struct Node* lchild, * rchild;
}Node;
typedef struct Tree {
Node* root;
int length;
}Tree;
Node* get_newNode(int val) {
Node* p = (Node*)malloc(sizeof(Node));
p->data = val;
p->lchild = p->rchild = nullptr;
return p;
}
Tree* get_newTree() {
Tree* t = (Tree*)malloc(sizeof(Tree));
t->root = nullptr;
t->length = 0;
return t;
}
Node* insert_node(Node* root, int val, int *flag) {
if (root == nullptr) {
*flag = 1;
return get_newNode(val);
}
if (root->data == val)return root;
if (root->data > val)root->lchild = insert_node(root->lchild, val, flag);
else root->rchild = insert_node(root->rchild, val, flag);
return root;
}
void insert(Tree* t, int val) {
if (t == nullptr)return;
int flag = 0;
t->root = insert_node(t->root, val, &flag);
t->length += flag;
return;
}
void clear_node(Node* node) {
if (node == nullptr)return;
clear_node(node->lchild);
clear_node(node->rchild);
free(node);
}
void clear(Tree* t) {
if (t == nullptr)return;
clear_node(t->root);
free(t);
return;
}
void pre_order_node(Node* root) {
if (root == nullptr)return;
printf("%d ", root->data);
pre_order_node(root->lchild);
pre_order_node(root->rchild);
return;
}
void pre_order(Tree* t) {
if (t == nullptr)return;
printf("pre_order : ");
pre_order_node(t->root);
printf("\n");
return;
}
void in_order_node(Node* root) {
if (root == nullptr)return;
in_order_node(root->lchild);
printf("%d ", root->data);
in_order_node(root->rchild);
return;
}
void in_order(Tree* t) {
if (t == nullptr)return;
printf("in_order : ");
in_order_node(t->root);
printf("\n");
return;
}
void post_order_node(Node* root) {
if (root == nullptr)return;
post_order_node(root->lchild);
post_order_node(root->rchild);
printf("%d ", root->data);
return;
}
void post_order(Tree* t) {
if (t == nullptr)return;
printf("post_order : ");
post_order_node(t->root);
printf("\n");
return;
}
void output_node(Node* root) {
if (root == nullptr)return;
printf("%d", root->data);
if (root->lchild == nullptr && root->rchild == nullptr)return;
printf("(");
output_node(root->lchild);
printf(",");
output_node(root->rchild);
printf(")");
return;
}
void output(Tree* t) {
if (t == nullptr)return;
printf("tree(%d) : ", t->length);
output_node(t->root);
printf("\n");
}
int main() {
srand(time(0));
Tree* tree = get_newTree();
#define MAX 10
for (int i = 1; i <= 10; i++) {
int val = rand() % 100;
insert(tree, val);
output(tree);
}
pre_order(tree);
in_order(tree);
post_order(tree);
#undef MAX
clear(tree);
return 0;
}