-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
88 lines (69 loc) · 2.15 KB
/
main.cpp
File metadata and controls
88 lines (69 loc) · 2.15 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
#include <iostream>
using namespace std;
// Implementing a Node structure for the binary search tree
struct Node {
int data;
Node* left;
Node* right;
Node(int value) {
data = value;
left = nullptr;
right = nullptr;
}
};
// Function to insert a value into the binary search tree
Node* insert(Node* root, int value) {
if (root == nullptr) {
return new Node(value);
}
if (value < root->data) {
root->left = insert(root->left, value);
} else if (value > root->data) {
root->right = insert(root->right, value);
}
return root;
}
// Function to find and extract subtree based on high and low values
Node* extractSubtree(Node* root, int low, int high) {
if (root == nullptr) return nullptr;
// If the current node's value is outside the range,
// recurse on left or right subtree based on the value
if (root->data < low) {
return extractSubtree(root->right, low, high);
} else if (root->data > high) {
return extractSubtree(root->left, low, high);
}
// If the current node's value is within the range,
// extract subtree recursively from left and right
root->left = extractSubtree(root->left, low, high);
root->right = extractSubtree(root->right, low, high);
return root;
}
// Function to perform in-order traversal
void inOrderTraversal(Node* root) {
if (root == nullptr) return;
inOrderTraversal(root->left);
cout << root->data << " ";
inOrderTraversal(root->right);
}
int main() {
Node* root = nullptr;
// Insert values into the binary search tree
root = insert(root, 50);
root = insert(root, 30);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 70);
root = insert(root, 60);
root = insert(root, 80);
// Define the range for extracting the subtree
int low = 20;
int high = 40;
// Extract subtree
root = extractSubtree(root, low, high);
// Print the extracted subtree (in-order traversal)
cout << "Subtree extracted based on range [" << low << ", " << high << "]:" << endl;
inOrderTraversal(root);
cout << endl;
return 0;
}