-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search_tree_insertion.cpp
More file actions
50 lines (46 loc) · 945 Bytes
/
binary_search_tree_insertion.cpp
File metadata and controls
50 lines (46 loc) · 945 Bytes
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
#include<iostream>
using namespace std;
struct Node
{
int key;
Node *left, *right;
};
void inorder(Node* root)
{
if(root!=NULL)
{
inorder(root->left); //left subtree
cout<<root->key<<"\t"; //value
inorder(root->right); //right subtree
}
}
Node* newnode(int val)
{
Node* temp=new Node();
//insert value in new node
temp->key=val;
temp->left=temp->right=NULL;
}
Node* insert(Node* root,int key)
{
//if node is null, means we have reached the leaf node
if(root==NULL)
return newnode(key);
//if key is smaller than root node value then insert on left subtree
if(key<root->key)
root->left=insert(root->left,key);
//if key is greater than root node value then insert on right subtree
if(key>root->key)
root->right=insert(root->right,key);
//unchanged pointer to root
return root;
}
int main()
{
Node* root=NULL;
root=insert(root,50);
insert(root,20);
insert(root,10);
insert(root,40);
inorder(root);
}