1 #include
2
3 struct tree_item
4 {
5 int numb;
6 uint32_t count;
7 struct tree_item *left;
8 struct tree_item *right;
9 };
10
11 typedef struct tree_item *Tree;
12
13 int add_to_tree(Tree *tree_p, int numb)
14 {
15 Tree tr=*tree_p;
16 Tree current_root=tr;
17
18 if(tr == NULL)
19 {
20 tr=(Tree)malloc(sizeof(struct tree_item));
21 if(tr==NULL)
22 {
23 return 1;
24 }
25
26 tr->numb=numb;
27 tr->count=1;
28 tr->left=NULL;
29 tr->right=NULL;
30
31 *tree_p=tr;
32
33 return 0;
34 }
35
36 while(1)
37 {
38 if(numb == current_root->numb)
39 {
40 current_root->count++;
41 return 0;
42 }
43
44 if(numb < current_root->numb)
45 {
46 if(current_root->left == NULL)
47 {
48 Tree tmp;
49
50 current_root->left=(Tree)malloc(sizeof(struct tree_item));
51 if(current_root->left == NULL)
52 {
53 return 1;
54 }
55
56 tmp=current_root->left;
57
58 tmp->numb=numb;
59 tmp->count=1;
60 tmp->left=NULL;
61 tmp->right=NULL;
62 return 0;
63 }
64
65 current_root=current_root->left;
66 continue;
67 }
68
69 if(numb > current_root->numb)
70 {
71 Tree tmp;
72
73 if(current_root->right == NULL)
74 {
75 current_root->right=(Tree)malloc(sizeof(struct tree_item));
76 if(current_root->right == NULL)
77 {
78 return 1;
79 }
80
81 tmp=current_root->right;
82
83 tmp->numb=numb;
84 tmp->count=1;
85 tmp->left=NULL;
86 tmp->right=NULL;
87 return 0;
88 }
89
90 current_root=current_root->right;
91 continue;
92 }
93
94 }
95
96 return 0;
97 }
98
99 void print_left_to_right(Tree tr)
100 {
101 if(tr==NULL)
102 {
103 return;
104 }
105
106 print_left_to_right(tr->left);
107 printf("numb = %d, count=%" PRIu32 "\n",tr->numb, tr->count);
108 print_left_to_right(tr->right);
109
110 }