bst to insert tree
struct Node
{
int data;
Node *left, *right;
};
// Function to create a new binary tree node having a given key
Node* newNode(int key)
{
Node* node = new Node;
node->data = key;
node->left = node->right = nullptr;
return node;
}
// Function to perform inorder traversal on the tree
void inorder(Node* root)
{
if (root == nullptr) {
return;
}
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}
// Recursive function to insert a key into a BST
Node* insert(Node* root, int key)
{
// if the root is null, create a new node and return it
if (root == nullptr) {
return newNode(key);
}
// if the given key is less than the root node, recur for the left subtree
if (key < root->data) {
root->left = insert(root->left, key);
}
// if the given key is more than the root node, recur for the right subtree
else {
root->right = insert(root->right, key);
}
return root;
}
4.2
5
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);
}
Thank you!
5
0
Are there any code examples left?
New code examples in category C++
-
C++ 2023-04-28 17:44:25
-
C++ 2022-03-27 19:20:39 lists occurrences of characters in the string c++
-
C++ 2022-03-27 18:00:14 variabili in c++
-
C++ 2022-03-27 17:10:08 repeat character n times c++
-
C++ 2022-03-27 15:50:07 delete an array c++
-
C++ 2022-03-27 15:40:12 C++ pointer to base class
-
C++ 2022-03-27 12:15:21 find the graph is minimal spanig tree or not
-
C++ 2022-03-27 11:30:15 multi variable assignment cpp
-
C++ 2022-03-27 11:05:17 c++ pi float
-
C++ 2022-03-27 10:20:12 why exceptions can lead to memory leaks