Answers for "How to insert a node in a BST"

1

java bst insert a node

...for inserting an element.

  Start from the root.
  Compare the element to be inserted with the root node. If it is less 
than root, then traverse the left subtree or traverse the right subtree.
  Traverse the subtree till the end of the desired subtree. 
  Insert the node in the appropriate subtree as a leaf node.
Posted by: Guest on October-12-2021
6

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;
}
Posted by: Guest on May-23-2021

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language