How do you implement a binary search tree (BST) in C++?
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int value) {
data = value;
left = right = NULL;
}
};
class BST {
public:
Node* insert(Node* root, int value) {
if (!root) return new Node(value);
if (value < root->data) root->left = insert(root->left, value);
else root->right = insert(root->right, value);
return root;
}
void inorder(Node* root) {
if (!root) return;
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}
};
int main() {
BST tree;
Node* root = NULL;
root = tree.insert(root, 50);
tree.insert(root, 30);
tree.insert(root, 70);
tree.insert(root, 20);
tree.insert(root, 40);
tree.insert(root, 60);
tree.insert(root, 80);
tree.inorder(root);
return 0;
}