File tree Expand file tree Collapse file tree 1 file changed +69
-0
lines changed Expand file tree Collapse file tree 1 file changed +69
-0
lines changed Original file line number Diff line number Diff line change 1+ #include < iostream>
2+
3+ class Node {
4+ public:
5+ int data;
6+ Node* left;
7+ Node* right;
8+
9+ Node (int data) {
10+ this ->data = data;
11+ this ->left = nullptr ;
12+ this ->right = nullptr ;
13+ }
14+ };
15+
16+ class BST {
17+ public:
18+ Node* root;
19+
20+ BST () {
21+ root = nullptr ;
22+ }
23+
24+ void insert (int data) {
25+ root = insertRecursive (root, data);
26+ }
27+
28+ Node* insertRecursive (Node* current, int data) {
29+ if (current == nullptr ) {
30+ return new Node (data);
31+ }
32+ if (data < current->data ) {
33+ current->left = insertRecursive (current->left , data);
34+ } else if (data > current->data ) {
35+ current->right = insertRecursive (current->right , data);
36+ }
37+ return current;
38+ }
39+
40+ void displayInOrder () {
41+ displayInOrderRecursive (root);
42+ }
43+
44+ void displayInOrderRecursive (Node* current) {
45+ if (current != nullptr ) {
46+ displayInOrderRecursive (current->left );
47+ std::cout << current->data << " " ;
48+ displayInOrderRecursive (current->right );
49+ }
50+ }
51+ };
52+
53+ int main () {
54+ BST tree;
55+
56+ tree.insert (4 );
57+ tree.insert (2 );
58+ tree.insert (6 );
59+ tree.insert (1 );
60+ tree.insert (3 );
61+ tree.insert (5 );
62+ tree.insert (7 );
63+
64+ std::cout << " In-order traversal: " ;
65+ tree.displayInOrder ();
66+ std::cout << std::endl;
67+
68+ return 0 ;
69+ }
You can’t perform that action at this time.
0 commit comments