inserting in binary search tree code example
Example 1: bst to insert tree
struct Node
{
int data;
Node *left, *right;
};
Node* newNode(int key)
{
Node* node = new Node;
node->data = key;
node->left = node->right = nullptr;
return node;
}
void inorder(Node* root)
{
if (root == nullptr) {
return;
}
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}
Node* insert(Node* root, int key)
{
if (root == nullptr) {
return newNode(key);
}
if (key < root->data) {
root->left = insert(root->left, key);
}
else {
root->right = insert(root->right, key);
}
return root;
}
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);
}