#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *left;
struct node *right;
} node_t;
typedef struct tree {
struct node *root;
} tree_t;
node_t *alloc_one(int data) {
node_t *p = (node_t *)malloc(sizeof(node_t));
p->data = data;
p->left = NULL;
p->right = NULL;
return p;
}
// 方法1:
void insert_one(tree_t *t, int data) {
node_t *new = alloc_one(data);
if (t == NULL) {
t = new;
} else {
node_t *tmp = t->root;
while (tmp) {
if (data < tmp->data) {
if (tmp->left == NULL) {
tmp->left = new;
return;
} else {
tmp = tmp->left;
}
} else if (data > tmp->data) {
if (tmp->right == NULL) {
tmp->right = new;
return;
} else {
tmp = tmp->right;
}
}
}
}
}
// 方法2:递归法
node_t *insert_one2(node_t *t, int data) {
node_t *new = alloc_one(data);
if (t == NULL) {
t->root = new;
} else {
node_t *tmp = t->root;
if (data < tmp->data) {
if (tmp->left == NULL) {
tmp->left = new;
return tmp->left;
} else {
insert_one2(tmp->left, data);
}
} else {
if (tmp->right == NULL) {
tmp->right = new;
return tmp->right;
} else {
insert_one2(tmp->right, data);
}
}
}
return t;
}
void inOrder(struct node_t *root, int *res, int *resSize) {
if (!root) {
return;
}
inOrder(root->left, res, resSize);
res[(*resSize++)] = root->data;
inOrder(root->right, res, resSize);
}
int* inOrderTraverse(struct node_t *root, int *returnSize) {
int *res = malloc(sizeof(int) * 100);
*returnSize = 0;
inOrder(root, res, returnSize);
}
int main() {
int dataList[3] = {3, 5, 19};
int i;
tree_t *my_tree;
my_tree->root = NULL;
for(i = 0; i < sizeof(dataList)/sizeof(int); i++) {
insert_one(my_tree, i);
}
return 0;
}