-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearchTreeInsert.cpp
More file actions
63 lines (55 loc) · 1.36 KB
/
BinarySearchTreeInsert.cpp
File metadata and controls
63 lines (55 loc) · 1.36 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
#include<iostream>
#include <cstdlib>
struct node{
int data;
struct node *left;
struct node *right;
};
struct node* newNode(int data) {
struct node* node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
struct node* insertBinarySearchTree(node *root , int data){
if(root== NULL){
root = newNode(data);
return root;
}
node *current = root;
node *prevoius = NULL;
while(current != NULL){
prevoius = current;
if(current->data > data ){
current = current->left;
}else{
current = current->right;
}
}
if(prevoius->data > data){
prevoius->left = newNode(data);
}else{
prevoius->right = newNode(data);
}
return root;
}
// V --> L --> R
void preorder(node *root){
if(root != NULL){
std::cout<<root->data<<"\t";
preorder(root->left);
preorder(root->right);
}
}
int main(){
// Insert into binary search tree
node *root = insertBinarySearchTree(NULL,10);
root = insertBinarySearchTree(root,5);
root = insertBinarySearchTree(root,-10);
root = insertBinarySearchTree(root,0);
root = insertBinarySearchTree(root,30);
root = insertBinarySearchTree(root,36);
// Printing Pre order
preorder(root);
}