Repository navigation
Expand file tree
/
Copy pathBST_insert.cpp
More file actions
113 lines (111 loc) · 2.33 KB
/
Copy pathBST_insert.cpp
File metadata and controls
113 lines (111 loc) · 2.33 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
#include <iostream>
template <class T>
struct Node
{
T data;
struct Node<T> *left;
struct Node<T> *right;
};
template <class T>
class Binary_Tree
{
private:
Node<T> *root;
int size;
public:
Binary_Tree()
{
size = 0;
}
void insert(const T &val)
{
Node<T> *newnode;
newnode = new Node<T>();
newnode->data = val;
newnode->left = newnode->right = NULL;
if (root == NULL)
{
root = newnode;
}
else
{
Node<T> *temp;
temp = root;
while (true)
{
if (val < temp->data)
{
if (temp->left == NULL)
{
temp->left = newnode;
return;
}
else
{
temp = temp->left;
}
}
else if (val > temp->data)
{
if (temp->right == NULL)
{
temp->right = newnode;
return;
}
else
{
temp = temp->right;
}
}
else
{
throw("duplicate");
}
}
}
}
void displayInOrder(Node<T> *node)
{
if (node != NULL)
{
displayInOrder(node->left);
std::cout << node->data << " ";
displayInOrder(node->right);
}
}
void display()
{
if (root == NULL)
{
std::cout << "The tree is empty." << std::endl;
}
else
{
std::cout << "In-order traversal: ";
displayInOrder(root->left);
std::cout << std::endl;
}
}
};
int main()
{
try
{
Binary_Tree<int> obj_1;
obj_1.insert(15);
obj_1.insert(7);
obj_1.insert(25);
obj_1.insert(5);
obj_1.insert(9);
obj_1.insert(8);
obj_1.insert(11);
obj_1.insert(23);
obj_1.insert(27);
obj_1.display();
}
catch (const char *msg)
{
std::cout << msg << '\n';
}
return 0;
}