-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path76_insertionBST.c
66 lines (58 loc) · 1.39 KB
/
76_insertionBST.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
56
57
58
59
60
61
62
63
64
65
66
#include<stdio.h>
#include<stdlib.h>
struct Node {
int data;
struct Node *left;
struct Node *right;
};
struct Node * createNode(int data){
struct Node *n = (struct Node *)malloc (sizeof(struct Node));
n -> data = data;
n -> left = NULL;
n -> right = NULL;
return n;
}
void insertion(struct Node * root, int data){
struct Node * prev = NULL;
struct Node * ptr =createNode(data);
while (root != NULL){
prev = root;
if (root -> data > data){
root = root -> left;
}
else if (root -> data < data){
root = root -> right;
}
else{
printf("Element already present\n");
return;
}
}
if (data > prev -> data){
prev -> right = ptr;
}else {
prev -> left = ptr;
}
}
void inOrder(struct Node *root){
if (root != NULL){
inOrder(root -> left);
printf("%d ",root -> data);
inOrder(root -> right);
}
}
int main(){
struct Node* p = createNode(5);
struct Node* p1 = createNode(3);
struct Node* p2 = createNode(6);
struct Node* p3 = createNode(1);
struct Node* p4 = createNode(4);
p -> left = p1;
p -> right = p2;
p1 -> left = p3;
p1 -> right = p4;
inOrder(p);
printf("\n");
insertion(p,4);
inOrder(p);
}