Algorithm


Problem Name: Data Structures - Binary Search Tree : Insertion

Problem Link: https://www.hackerrank.com/challenges/binary-search-tree-insertion/problem?isFullScreen=true

In this HackerRank in Data Structures - Binary Search Tree : Insertion solutions

You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function.

Input Format

You are given a function,

Node * insert (Node * root ,int data) {

}

Constraints

  • No. of nodes in the tree <= 500

Output Format

Return the root of the binary search tree after inserting the value into the tree.

Sample Input

        4
       / \
      2   7
     / \
    1   3

The value to be inserted is 6.

Sample Output

         4
       /   \
      2     7
     / \   /
    1   3 6

 

 

 

Code Examples

#1 Code Example with C Programming

Code - C Programming


#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

struct node {
    
    int data;
    struct node *left;
    struct node *right;
  
};

void preOrder( struct node *root) {
  
	if( root == NULL ) 
      return;
	printf("%d ",root->data);
	preOrder(root->left);
	preOrder(root->right);
  
}

/* you only have to complete the function given below.  
node is defined as  

struct node {
    
    int data;
    struct node *left;
    struct node *right;
  
};

*/
struct node* insert( struct node* root, int data ) {
    
    if(root == NULL){
         root = malloc(sizeof(struct node));
            root->data = data;
            root->left = NULL;
            root->right = NULL;
     
    }else if(data  <  root->data){
            root->left = insert(root->left, data);
    }else{
            root->right = insert(root->right, data);
     }
    return root;   
       
}


int main() {
  
    struct node* root = NULL;
    
    int t;
    int data;

    scanf("%d", &t);

    while(t-- > 0) {
        scanf("%d", &data);
        root = insert(root, data);
    }
  
	preOrder(root);
    return 0;
}

Copy The Code & Try With Live Editor

#2 Code Example with C++ Programming

Code - C++ Programming


#include <bits/stdc++.h>

using namespace std;

class Node {
    public:
        int data;
        Node *left;
        Node *right;
        Node(int d) {
            data = d;
            left = NULL;
            right = NULL;
        }
};

class Solution {
    public:
    
    void preOrder(Node *root) {
        
        if( root == NULL )
            return;
      
        std::cout << root->data << " ";
        
        preOrder(root->left);
        preOrder(root->right);
    }

/*
Node is defined as 

class Node {
    public:
        int data;
        Node *left;
        Node *right;
        Node(int d) {
            data = d;
            left = NULL;
            right = NULL;
        }
};

*/

    Node * insert(Node * root, int value) {
  
  if(root==NULL) {
    Node* newNode;
    newNode = (Node*)malloc(sizeof(Node));
    newNode->left = NULL;
    newNode->right = NULL;
    newNode->data = value;
    return newNode;
  }
  
  if(value  < = root->data)
    root->left = insert(root->left, value);
  else
    root->right = insert(root->right, value);
  
  return root;
}

};

int main() {
  
    Solution myTree;
    Node* root = NULL;
    
    int t;
    int data;

    std::cin >> t;

    while(t-- > 0) {
        std::cin >> data;
        root = myTree.insert(root, data);
    }
    
    myTree.preOrder(root);
  
    return 0;
}
Copy The Code & Try With Live Editor

#3 Code Example with Java Programming

Code - Java Programming


import java.util.*;
import java.io.*;

class Node {
    Node left;
    Node right;
    int data;
    
    Node(int data) {
        this.data = data;
        left = null;
        right = null;
    }
}

class Solution {
   
    public static void preOrder( Node root ) {
      
        if( root == null)
            return;
      
        System.out.print(root.data + " ");
        preOrder(root.left);
        preOrder(root.right);
     
    }

 /* Node is defined as :
 class Node 
    int data;
    Node left;
    Node right;
    
    */

public static Node insert(Node root,int value)
{
    if(root == null) {
        root = new Node(value);
    } else if(value < root.data){
        root.left = insert(root.left,value>;
    } else if(value > root.data) {
        root.right = insert(root.right,value);
    }
    
    return root;
    
}


    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int t = scan.nextInt();
        Node root = null;
        while(t-- > 0) {
            int data = scan.nextInt();
            root = insert(root, data);
        }
        scan.close();
        preOrder(root);
    }   
}
Copy The Code & Try With Live Editor

#4 Code Example with Python Programming

Code - Python Programming


class Node:
    def __init__(self, info):
        self.info = info  
        self.left = None  
        self.right = None 
        self.level = None 

    def __str__(self):
        return str(self.info) 

def preOrder(root):
    if root == None:
        return
    print (root.info, end=" ")
    preOrder(root.left)
    preOrder(root.right)
    
class BinarySearchTree:
    def __init__(self): 
        self.root = None

#Node is defined as
#self.left (the left child of the node)
#self.right (the right child of the node)
#self.info (the value of the node)

    def insert(self, val):
        if self.root is None:
            self.root=Node(val)
        else:
            current = self.root
            while True:
                if val < current.info:
                    if current.left is None:
                        current.left=Node(val)
                        break
                    else:
                        current=current.left
                else:
                    if current.right is None:
                        current.right=Node(val)
                        break
                    else:
                        current=current.right

tree = BinarySearchTree()
t = int(input())

arr = list(map(int, input().split()))

for i in range(t):
    tree.insert(arr[i])

preOrder(tree.root)
Copy The Code & Try With Live Editor
Advertisements

Demonstration


Previous
[Solved] Tree : Tree: Level Order Traversal solution in Hackerrank - Hacerrank solution C, C++, java,js, Python
Next
[Solved] Tree : Binary Search Tree : Lowest Common Ancestor solution in Hackerrank - Hacerrank solution C, C++, java,js, Python