/
sortedBinaryTree.c
55 lines (48 loc) · 1.01 KB
/
sortedBinaryTree.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# include <stdio.h>
# include <stdlib.h>
struct node{
int data;
struct node* left;
struct node* right;
};
void addNode(struct node** root, int data){
if(*root == NULL){
struct node* temp;
temp = (struct node*)malloc(sizeof(struct node));
temp -> data = data;
temp -> left = NULL;
temp -> right = NULL;
*root=temp;
}
if(data >(*root)->data)
{
addNode((*root)->right,data);
}
else if(data < (*root)->data)
{
addNode((*root)->left,data);
}
}
void printInorder(struct node* root){
if(root == NULL){
return;
}
printInorder(root->left);
printf(" %d ", root->data);
printInorder(root->right);
}
int main(){
struct node* root = NULL;
int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
breakArray(&root, array, 9);
printInorder(root);
}
int breakArray(struct node** root, int array[], int length){
if(length == 1)
return array[0];
int data;
data = array[(length/2)];
addNode(root, data);
breakArray(root, array, (length/2));
breakArray(root, array+(length/2), (length/2));
}