forked from mbakrol/MB-HacktoberFest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary_tree.cpp
70 lines (67 loc) · 1.41 KB
/
binary_tree.cpp
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
#include<iostream>
using namespace std;
struct bintree_node{
bintree_node *left;
bintree_node *right;
int data;
} ;
class bst{
bintree_node *root;
public:
bst(){
root=NULL;
}
int isempty() {
return(root==NULL);
}
void insert(int item);
void displayBinTree();
void printBinTree(bintree_node *);
};
void bst::insert(int item){
bintree_node *p=new bintree_node;
bintree_node *parent;
p->data=item;
p->left=NULL;
p->right=NULL;
parent=NULL;
if(isempty())
root=p;
else{
bintree_node *ptr;
ptr=root;
while(ptr!=NULL){
parent=ptr;
if(item>ptr->data)
ptr=ptr->right;
else
ptr=ptr->left;
}
if(item<parent->data)
parent->left=p;
else
parent->right=p;
}
}
void bst::displayBinTree(){
printBinTree(root);
}
void bst::printBinTree(bintree_node *ptr){
if(ptr!=NULL){
printBinTree(ptr->left);
cout<<" "<<ptr->data<<" ";
printBinTree(ptr->right);
}
}
int main(){
bst b;
b.insert(20);
b.insert(10);
b.insert(5);
b.insert(15);
b.insert(40);
b.insert(45);
b.insert(30);
cout<<"Binary tree created: "<<endl;
b.displayBinTree();
}