creating a binary search tree code example
Example 1: binary tree search
void searchNode(Node *root, int data)
{
if(root == NULL)
{
cout << "Tree is empty\n";
return;
}
queue<Node*> q;
q.push(root);
while(!q.empty())
{
Node *temp = q.front();
q.pop();
if(temp->data == data)
{
cout << "Node found\n";
return;
}
if(temp->left != NULL)
q.push(temp->left);
if(temp->right != NULL)
q.push(temp->right);
}
cout << "Node not found\n";
}
Example 2: insert binary search tree
void BSNode::insert(std::string value) {
if (this->_data == value) {
_count++;
return;
}
if (this->_data > value) {
if (this->getLeft() == nullptr) {
this->_left = new BSNode(value);
}
this->getLeft()->insert(value);
return;
}
if (this->getRight() == nullptr) {
this->_right = new BSNode(value);
return;
}
this->getRight()->insert(value);
}