# 二叉树和二叉树排序

1 struct tree
2 {
3     int data;
4     struct tree *child_l;
5     struct tree *child_r;
6 };

1 void read_tree(struct tree *t) {
2     printf("%d\n",t->data);
3     if (t->child_l != NULL)
5     if (t->child_r != NULL)
7 }

1 struct stack {
2     struct tree* stack_value[10];
3     int top;
4 };

1 #define NOMAL_COUNT 1
2
3 struct stack* init_stack() {
4     struct stack *s = (struct stack *) calloc(NOMAL_COUNT, sizeof(struct stack));
5     s->top = -1;
6     return s;
7 }

 1 void stack_push(struct stack *s, struct tree *t) {
2     s->top++;
3     s->stack_value[s->top] = t;
4 }
5
6 struct tree* stack_pop(struct stack *s) {
7     struct tree *t = s->stack_value[s->top];
8     s->top--;
9     return t;
10 }

 1 void read_tree2(struct tree *t) {
2     struct tree * temp = t;
3     struct stack *s = init_stack();
4
5     while (temp != NULL || s->top != -1) {
6         while (temp != NULL) {
7             printf("%d\n", temp->data);
8             stack_push(s, temp);
9             temp = temp->child_l;
10         }
11         if (s->top != -1) {
12             temp = stack_pop(s);
13             temp = temp->child_r;
14         }
15     }
16 }

 1 struct tree *t = (struct tree *) calloc(NOMAL_COUNT, sizeof(struct tree));
2 struct tree *temp;
3 t->data = 1;
4 t->child_l = (struct tree *) calloc(NOMAL_COUNT, sizeof(struct tree));
5 temp = t->child_l;
6 temp->data = 2;
7 temp->child_l = (struct tree *) calloc(NOMAL_COUNT, sizeof(struct tree));
8 temp->child_l->data = 4;
9 temp->child_r = (struct tree *) calloc(NOMAL_COUNT, sizeof(struct tree));
10 temp->child_r->data = 5;
11 t->child_r = (struct tree *) calloc(NOMAL_COUNT, sizeof(struct tree));
12 t->child_r->data = 3;

 1 void add_tree(struct tree *t, int number) {
2     if (t->data > number) {
3         if (t->child_l != NULL) {
5         } else {
6             t->child_l = (struct tree *) calloc(NOMAL_COUNT, sizeof(struct tree));
7             t->child_l->data = number;
8         }
9     } else {
10         if (t->child_r != NULL) {
12         } else {
13             t->child_r = (struct tree *) calloc(NOMAL_COUNT, sizeof(struct tree));
14             t->child_r->data = number;
15         }
16     }
17 }

1 // 中序遍历二叉树
2 void read_tree(struct tree *t) {
3     if (t->child_l != NULL)
5     printf("%d\n",t->data);
6     if (t->child_r != NULL)
8 }

 1 int main(int argc, char const *argv[])
2 {
3     int numbers[] = {8, 7, 1, 4, 3, 5, 9, 19, 13, 11, 15, 20, 16, 2, 6};
4     struct tree *t = (struct tree *) calloc(NOMAL_COUNT, sizeof(struct tree));
5     t->data = numbers[0];
6     for (int i = 1; i < 15; i++) {
8     }
10     return 0;
11 }

1
2
3
4
5
6
7
8
9
11
13
15
16
19
20

posted @ 2019-01-30 18:36  Summer7C  阅读(145)  评论(0编辑  收藏