1 # include<stdio.h> 2 3 struct dll{ 4 struct Element* head; 5 int size; 6 }; 7 8 struct Element{ 9 int value; 10 struct Element* p; 11 struct Element* r; 12 }; 13 14 typedef struct Element Element; 15 typedef struct dll dll; 16 17 void add(dll* m, int k){ //添加树分支 18 Element* ptr; 19 ptr = (int *)malloc(10 * sizeof(int)); 20 ptr->value = k; 21 ptr->r = NULL; 22 ptr->p = NULL; 23 Element* head = m->head; 24 while (1){ 25 int a = ((head->value) > k); 26 int b = (head->p == NULL); 27 int c = (head->r == NULL); 28 if (a == 1) 29 { 30 if (b == 1) 31 { 32 head->p = ptr; break; 33 } 34 else 35 head = head->p; 36 } 37 else 38 { 39 if (c == 1) 40 { 41 head->r = ptr; break; 42 } 43 else 44 head = head->r; 45 } 46 } 47 } 48 void init(dll* m, int k){ //树初始化第一个元素 49 Element* ptr; 50 ptr = (int *)malloc(10 * sizeof(int)); 51 ptr->value = k; 52 m->head = ptr; 53 ptr->r = NULL; 54 ptr->p = NULL; 55 m->size = m->size + 1; 56 } 57 58 void ChangLeftRight(dll* t){ //调换左右孩子 59 Element* m = t->head; 60 Ct(m); 61 } 62 63 int Ct(Element* t){ 64 int tmp=0; 65 if ((t->p != NULL) && (t->r != NULL)) 66 { 67 tmp = t->p->value; 68 t->p->value = t->r->value; 69 t->r->value = tmp; 70 } 71 if ((t->p != NULL)) 72 Ct(t->p); 73 if ((t->r != NULL)) 74 Ct(t->r); 75 76 if (t == NULL) 77 return 1; 78 } 79 80 void BlE(Element* k){ 81 printf("%d ", k->value); 82 if (k->p != NULL) 83 BlE(k->p); 84 if (k->r != NULL) 85 BlE(k->r); 86 } 87 88 void Bl(dll* t){ //前序遍历 89 90 Element* head; 91 head = (int *)malloc(10 * sizeof(int)); 92 head = t->head; 93 BlE(head); 94 95 } 96 97 void main(){ 98 dll* t; 99 t = (int *)malloc(20 * sizeof(int)); 100 t->size = 0; 101 t->head = NULL; 102 init(t,30); 103 add(t, 6); 104 add(t, 2); 105 add(t, 5); 106 add(t, 56); 107 add(t, 36); 108 add(t, 9); 109 add(t, 98); 110 Bl(t); 111 ChangLeftRight(t); 112 printf(" "); 113 Bl(t); 114 system("pause"); 115 }