137k views
2 votes
In C++ create an implementation a binary search tree

Please use preorder traversal on the following set: { 11, 22,
14, 10, 3, 27 }.

1 Answer

2 votes

Final answer:

To create a binary search tree in C++, define a Node structure with a constructor, and implement functions to insert elements and perform a preorder traversal. Insert the given set into the BST and use the traversal function to output the tree in preorder.

Step-by-step explanation:

Implementing a Binary Search Tree in C++

To implement a binary search tree (BST) in C++, we'll first define a structure for the nodes and then create functions for inserting nodes and performing a preorder traversal.

Defining the Node Structure:


struct Node {
int data;
Node* left;
Node* right;

Node(int value) : data(value), left(nullptr), right(nullptr) {}
};

Insert Function:


Node* insert(Node* root, int data) {
if (!root) {
return new Node(data);
}
if (data < root->data) {
root->left = insert(root->left, data);
} else if (data > root->data) {
root->right = insert(root->right, data);
}
return root;
}

Preorder Traversal Function:


void preorderTraversal(Node* root) {
if (root) {
cout << root->data << ' ';
preorderTraversal(root->left);
preorderTraversal(root->right);
}
}

For the given set { 11, 22, 14, 10, 3, 27 }, you would insert the elements in the order they're given to build the BST. Once the tree is created, call the preorderTraversal function to print the elements in preorder.

User Raviraj Jadeja
by
6.9k points