forked from bhaveshkalra/DSA-codes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBalanced_Binary_Tree_using_Sorted_Array.c
More file actions
151 lines (68 loc) · 1.99 KB
/
Copy pathBalanced_Binary_Tree_using_Sorted_Array.c
File metadata and controls
151 lines (68 loc) · 1.99 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
/*
* C Program to Construct a Balanced Binary Tree using Sorted Array
* 40
* / \
* 20 60
* / \ \
* 10 30 80
* \
* 90
* (Given Binary Search Tree)
*/
#include <stdio.h>
#include <stdlib.h>
struct btnode
{
int value;
struct btnode *l;
struct btnode *r;
};
typedef struct btnode N;
N* bst(int arr[], int first, int last);
N* new(int val);
void display(N *temp);
int main()
{
int arr[] = {10, 20, 30, 40, 60, 80, 90};
N *root = (N*)malloc(sizeof(N));
int n = sizeof(arr) / sizeof(arr[0]), i;
printf("Given sorted array is\n");
for (i = 0;i < n;i++)
printf("%d\t", arr[i]);
root = bst(arr, 0, n - 1);
printf("\n The preorder traversal of binary search tree is as follows\n");
display(root);
printf("\n");
return 0;
}
/* To create a new node */
N* new(int val)
{
N* node = (N*)malloc(sizeof(N));
node->value = val;
node->l = NULL;
node->r = NULL;
return node;
}
/* To create a balanced binary search tree */
N* bst(int arr[], int first, int last)
{
int mid;
N* temp = (N*)malloc(sizeof(N));
if (first > last)
return NULL;
mid = (first + last) / 2;
temp = new(arr[mid]);
temp->l = bst(arr, first, mid - 1);
temp->r = bst(arr, mid + 1, last);
return temp;
}
/* To display the preorder */
void display(N *temp)
{
printf("%d->", temp->value);
if (temp->l != NULL)
display(temp->l);
if (temp->r != NULL)
display(temp->r);
}