#includeusing namespace std; class Node { public: int value; Node* left; Node* right; Node(int value) { this->value = value; left = NULL; right = NULL; } }; Node* insert(Node* root, int value) { if (!root) { return new Node(value); } else { if (value <= root->value) { root->left = insert(root->left, value); } else { root->right = insert(root->right, value); } } return root; } int main() { Node* root = NULL; root = insert(root, 5); root = insert(root, 3); root = insert(root, 8); root = insert(root, 1); root = insert(root, 4); return 0; }
#includeusing namespace std; class Node { public: int value; Node* left; Node* right; Node(int value) { this->value = value; left = NULL; right = NULL; } }; void inorder(Node* root) { if(!root) return; inorder(root->left); cout << root->value << " "; inorder(root->right); } int main() { Node* root = new Node(5); root->left = new Node(3); root->right = new Node(8); root->left->left = new Node(1); root->left->right = new Node(4); cout<<"Inorder Traversal:"<
This code snippet traverses the BST using Inorder Traversal technique and prints the nodes visited in ascending order.
Package library: None required - uses standard C++ libraries.
3. Searching for an element in the BST#includeThis code snippet searches for an element in the BST and prints "Value found in BST" if the element is present and "Value not found in BST" if the element is not present. Package library: None required - uses standard C++ libraries.using namespace std; class Node { public: int value; Node* left; Node* right; Node(int value) { this->value = value; left = NULL; right = NULL; } }; Node* search(Node* root, int value) { if (!root || root->value == value) { return root; } if (root->value > value) { return search(root->left, value); } return search(root->right, value); } int main() { Node* root = new Node(5); root->left = new Node(3); root->right = new Node(8); root->left->left = new Node(1); root->left->right = new Node(4); int searchValue = 3; Node* foundNode = search(root, searchValue); if (foundNode != NULL) { cout << "Value found in BST" << endl; } else { cout << "Value not found in BST" << endl; } return 0; }