-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary search tree.cpp
59 lines (50 loc) · 1.27 KB
/
binary search 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
#include <iostream>
using namespace std;
// Binary Search Tree Node
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// Binary Search Tree Class
class BST {
public:
TreeNode *root;
BST() {
root = NULL;
}
// Insert Node in Binary Search Tree
TreeNode* insert(TreeNode* root, int val) {
if (root == NULL) {
return new TreeNode(val);
}
if (val < root->val) {
root->left = insert(root->left, val);
} else {
root->right = insert(root->right, val);
}
return root;
}
// Traverse Binary Search Tree
void traverse(TreeNode* root) {
if (root != NULL) {
traverse(root->left);
cout << root->val << " ";
traverse(root->right);
}
}
};
int main() {
BST bst;
bst.root = bst.insert(bst.root, 10);
bst.insert(bst.root, 5);
bst.insert(bst.root, 20);
bst.insert(bst.root, 3);
bst.insert(bst.root, 8);
bst.insert(bst.root, 15);
bst.insert(bst.root, 25);
cout << "In-Order Traversal of Binary Search Tree: ";
bst.traverse(bst.root);
return 0;
}