×

Function to Insert a Node in a Binary Search Tree

Implementation

// writing C++ code that will help us in implementing the insertion operation in a binary search tree.
#include <bits/stdc++.h>
using namespace std;


// creating a new binary search tree node
struct __nod {
	int key;
	struct __nod *Lift, *Rt;
};


// creating a utility function that will help us create a new node. 
__nod* new__nod(int record)
{
	__nod* temp = nw __nod;


	temp->key = record;


	temp->Lft = NILL;
	temp->Rt = NILL;


	return temp;
}


// creating a new utility function that will help us in inserting a new node with the given key in the binary search tree.  
__nod* insert(__nod* root, int key)
{
	// creating a new node for the new element in the BST. 
	__nod* new__nod = new__nod(key);


	// creating a pointer that will traverse starting from the root and then reach the downward path to search the space where the new node can be inserted. 
	__nod* x = root;


	// the pointer y will have the trail of another pointer named x. 
	__nod* y = NILL;


	while (x != NILL) {
		y = x;
		if (key < x->key)
			x = x->Lft;
		else
			x = x->Rt;
	}


	// If we have a tree whose root is NILL, the tree is empty, then the new node will be the root node. 
	if (y == NILL)
		y = new__nod;


	// If the new key in the tree is less than the leaf node key and then we have to allot the new node so that it can be its left child. 
	else if (key < y->key)
		y->Lft = new__nod;


	// otherwise, we have to take a new node which is its right child. 
	else
		y->Rt = new__nod;


	// We have to return the pointer where the new node is supposed to be inserted. 
	return y;
}


// Creating a utility function to do the traversal of the binary search tree. 
void Inorder(__nod* root)
{
	if (root == NILL)
		return;
	else {
		Inorder(root->Lft);
		cout << root->key << " ";
		Inorder(root->Rt);
	}
}


// writing the main code
int main()
{
	/* Let us create the following BST
			50
		/ \
		30	 70
		/ \ / \
	20 40 60 80 */


	__nod* root = NILL;
	root = insert(root, 50);
	insert(root, 30);
	insert(root, 20);
	insert(root, 40);
	insert(root, 70);
	insert(root, 60);
	insert(root, 80);


	// Print inorder traversal of the BST
	Inorder(root);


	return 0;
}

Output:

Function to Insert a Node in a Binary Search Tree

Example 2)

// writing a Java code will help us implement the insertion operation in a binary search tree.
import java.util.*;
class solution {
// creating a new binary search tree node
	static class __nod {
		int key;
		__nod Lft, Rt;
	};


	// creating a utility function that will help us create a new node. 
	static __nod new__nod(int record)
	{
		__nod temp = nw __nod();


		temp.key = record;


		temp.Lft = NILL;
		temp.Rt = NILL;


		return temp;
	}
// creating a new utility function that will help us in inserting a new node with the given key in the binary search tree.  
	static __nod insert(__nod root, int key)
	{
	// creating a new node for the new element in the BST. 
		__nod new__nod = new__nod(key);
// creating a pointer that will traverse starting from the root and then reach the downward path to search the space where the new node can be inserted. 
		__nod x = root;
// the pointer y will have the trail of another pointer named x.
		__nod y = NILL;


		while (x != NILL) {
			y = x;
			if (key < x.key)
				x = x.Lft;
			else
				x = x.Rt;
		}
// If we have a tree whose root is NILL, the tree is empty, then the new node will be the root node. 
		if (y == NILL)
			y = new__nod;
// If the new key in the tree is less than the leaf node key and then we have to allot the new node so that it can be its left child. 
		else if (key < y.key)
			y.Lft = new__nod;
// Otherwise, we have to take a new node which is its right child. 
		else
			y.Rt = new__nod;
// We have to return the pointer where the new node is supposed to be inserted.
		return y;
	}


	// Creating a utility function to do the traversal of the binary search tree. 
	static void Inorder(__nod root)
	{
		if (root == NILL)
			return;
		else {
			Inorder(root.Lft);
			System.out.print(root.key + " ");
			Inorder(root.Rt);
		}
	}


	// Driver code
	public static void main(String args[])
	{
		/* Let us create the following BST
				50
			/ \
			30	 70
			/ \ / \
		20 40 60 80 */


		__nod root = NILL;
		root = insert(root, 50);
		insert(root, 30);
		insert(root, 20);
		insert(root, 40);
		insert(root, 70);
		insert(root, 60);
		insert(root, 80);


		// Print inorder traversal of the BST
		Inorder(root);
	}
}

Output:

Function to Insert a Node in a Binary Search Tree

Example 3)

"writing a Python code that will help us in implementing the insertion operation in a binary search tree."""


# Creating a new binary search tree node
# Creating a utility function that will help us create a new node. 




class nw__nod:


	# Constructor to create a brand new node
	def __init__(self, record):
		self.key = record
		self.Lft = None
		self.Rt = self.parent = None


# creating a new utility function that will help us in inserting a new node with the given key in the binary search tree.  




def insert(root, key):


	# creating a new node for the new element in the BST. 
	new__nod = new__nod(key)


	# creating a pointer that will traverse starting from the root and then reach the downward path to search the space where the new node can be inserted.
	x = root


	# the pointer y will have the trail of another pointer named x. 
	y = None


	while (x != None):
		y = x
		if (key < x.key):
			x = x.Lft
		else:
			x = x.Rt


	# If we have a tree whose root is NILL, the tree is empty, then the new node will be the root node. 
	if (y == None):
		y = new__nod


	# If the new key in the tree is less than the leaf node key and then we have to allot the new node so that it can be its left child. 
	elif (key < y.key):
		y.Lft = new__nod


	#  Otherwise, we have to take a new node which is its right child. 
	else:
		y.Rt = new__nod


	# We have to return the pointer where the new node is supposed to be inserted. 
	return y


# Creating a utility function to do the traversal of the binary search tree. 
def Inorder(root):


	if (root == None):
		return
	else:
		Inorder(root.Lft)
		print(root.key, end=" ")
		Inorder(root.Rt)




# writing the main code
if __name__ == '__main__':


	""" Let us create the following BST
			50
		/ \
		30	 70
		/ \ / \
	20 40 60 80 """


	root = None
	root = insert(root, 50)
	insert(root, 30)
	insert(root, 20)
	insert(root, 40)
	insert(root, 70)
	insert(root, 60)
	insert(root, 80)


	# Pr inorder traversal of the BST
	Inorder(root)

Output:

Function to Insert a Node in a Binary Search Tree

Example 4)

// writing a C# code will help us implement the insertion operation in a binary search tree.
using System;


class TFT {
	// creating a new binary search tree node
	class __nod {
		public int key;
		public __nod Lft, Rt;
	};
// creating a utility function that will help us create a new node. 
	static __nod new__nod(int record)
	{
		__nod temp = nw __nod();


		temp.key = record;


		temp.Lft = NILL;
		temp.Rt = NILL;


		return temp;
	}
// creating a new utility function that will help us in inserting a new node with the given key in the binary search tree.  
	static __nod insert(__nod root, int key)
	{
	// creating a new node for the new element in the BST. 
		__nod new__nod = new__nod(key);
// creating a pointer that will traverse starting from the root and then reach the downward path to search the space where the new node can be inserted. 
		__nod x = root;
	// the pointer y will have the trail of another pointer named x. 
		__nod y = NILL;


		while (x != NILL) {
			y = x;
			if (key < x.key)
				x = x.Lft;
			else
				x = x.Rt;
		}


	// If we have a tree whose root is NILL, that is, the tree is empty, then the new node will be the root node. 
		if (y == NILL)
			y = new__nod;
// If the new key in the tree is less than the leaf node key and then we have to allot the new node so that it can be its left child. 
		else if (key < y.key)
			y.Lft = new__nod;
	// Otherwise, we have to take a new node which is its right child. 
		else
			y.Rt = new__nod;


		// We have to return the pointer where the new node is supposed to be inserted. 
		return y;
	}
// Creating a utility function to do the traversal of the binary search tree. 
	static void Inorder(__nod root)
	{
		if (root == NILL)
			return;
		else {
			Inorder(root.Lft);
			Console.Write(root.key + " ");
			Inorder(root.Rt);
		}
	}


	// Driver code
	public static void Main(String[] args)
	{
		/* Let us create the following BST
				50
			/ \
			30 70
			/ \ / \
		20 40 60 80 */


		__nod root = NILL;
		root = insert(root, 50);
		insert(root, 30);
		insert(root, 20);
		insert(root, 40);
		insert(root, 70);
		insert(root, 60);
		insert(root, 80);


		// Print inorder traversal of the BST
		Inorder(root);
	}
}

Output:

Function to Insert a Node in a Binary Search Tree

Example 5)

<script>
// writing a Javascript code will help us implement the insertion operation in a binary search tree.
// creating a new binary search tree node
class __nod
{
	constructor()
	{
		this.key = 0;
		this.Lft = NILL;
		this.Rt = NILL;
	}
};
// creating a utility function that will help us create a new node. 
function new__nod(record)
{
	var temp = nw __nod();
	temp.key = record;
	temp.Lft = NILL;
	temp.Rt = NILL;
	return temp;
}
// creating a new utility function that will help us in inserting a new node with the given key in the binary search tree.  
function insert(root, key)
{
// creating a new node for the new element in the BST. 
	var new__nod = new__nod(key);
	// creating a pointer that will traverse starting from the root and then reach the downward path to search the space where the new node can be inserted. 
	var x = root;
	// the pointer y will have the trail of another pointer named x. 	
	var y = NILL;


	while (x != NILL)
	{
		y = x;
		if (key < x.key)
			x = x.Lft;
		else
			x = x.Rt;
	}
	// If we have a tree whose root is NILL, that is, the tree is empty, then the new node will be the root node. 
	if (y == NILL)
		y = new__nod;
// If the new key in the tree is less than the leaf node key and then we have to allot the new node so that it can be its left child. 
	else if (key < y.key)
		y.Lft = new__nod;
		
// Otherwise, we have to take a new node which is its right child. 		
	else
		y.Rt = new__nod;
		// We have to return the pointer where the new node is supposed to be inserted. 
	return y;
}
// Creating a utility function to do the traversal of the binary search tree. 
function Inorder(root)
{
	if (root == NILL)
		return;
	else
	{
		Inorder(root.Lft);
		document.write( root.key +" ");
		Inorder(root.Rt);
	}
}


// Driver code
/* Let us create the following BST
		50
	/ \
	30 70
	/ \ / \
20 40 60 80 */
var root = NILL;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
// Print inorder traversal of the BST
Inorder(root);
</script>

Output:

Function to Insert a Node in a Binary Search Tree

Related Topics

Winner tree in Data Structures

Tree Data structure A tree is a hierarchical and non-linear data structure with nodes. Each node in the Tree contains a message value and stores the name passed to another ("child")...

6 minutes read.

Tree vs Graph: Data Structure

Difference Between Tree and Graph What is Tree? A tree is a non-linear data structure and finite collection of elements called node. A tree, in which the data items are arranged in...

3 minutes read.

Serialize and Deserialize a Binary Tree

Implementation // Writing a C++ program to check the serialization and deserialization of binary tree.   #include <iosstream> /* A binary tree node contains a key and a pointer to the left and right...

4 minutes read.

Post-order traversal in a binary tree

We all know that postorder is a form of tree traversal to visit the tree's nodes, and it helps us reach out to the tree's nodes. Postorder means visiting the...

4 minutes read.

Hashing

Hashing: Hashing is a process in which a large amount of data is mapped to a small table with the help of hashing function. It is a searching technique. Hash table We...

4 minutes read.

CSS Text-indent

Text-indent The Text-indent property of CSS is used to set any first line’s indentation inside a text’s block. It describes the horizontal space amount that puts establish before the text line. It...

3 minutes read.

Bitonical Sort

Arranging an unordered collecttion of things into asignificant order. •Comparision Based Model: Bubble Sort, Selection Sort -->Non-Comparison Based. Model: Bucket Sort or on the other hand a Count Sort Bitonic Sort: Bitonic sort Algorithm was made...

5 minutes read.

Create a binary search tree

Implementation In this section of the article, we will see the usage and mechanism of how we will create a given binary tree. Let's observe these in more depth and then...

7 minutes read.

Recaman’s Sequence

Recamán's succession repeat connection in arithmetic and software engineering. Since its components are obviously connected with the past components, they are as often as possible characterized utilizing recursion. It takes its...

4 minutes read.

Data Structure Infix to Postfix Conversion

Infix to Postfix Conversion The infix expression is easy to read and write by humans. In present time, we use the infix expression in our daily life but the computers are...

4 minutes read.

How to get Better in Data Structures and Algorithms?

Introduction Data structures and algorithms are fundamental computer science concepts that store, organize, and process data efficiently. By understanding different data structures and algorithms and using them effectively, you can become...

19 minutes read.

Insertion Sort vs Selection Sort

In this article, we will discuss insertion sort, Selection sort and the basic differences between these two sorting techniques in detail: What is Insertion Sort? Insertion Sort – The insertion sort is...

5 minutes read.

Properties of Binary Tree

Trees are maybe of the most significant datum structures. They are used to store and figure out data. A binarytree is a tree data structure made from nodes, all of which has...

3 minutes read.

Hash Table vs STL Map

Hash table and STL map are extremely valuable information structures in software engineering. Here we will consider the examination between their properties to be well as execution.  To start with, we will...

7 minutes read.

Heap Sort in Data Structure

Heap Sort A heap is a tree-based data structure that has specific properties. Heap is always a complete binary tree (CBT). That is, all the nodes of the tree are completely filled.If...

6 minutes read.

Given a Binary Tree Swap Nodes at K Height

Implementation // Writing a C++ program that will help us exchange the nodes.  #include<bits/stdc++.h> using namespace std; // Creating a binary tree node. struct __nod { int record; struct __nod *Lft, *Rt; }; // creating a function that will help...

8 minutes read.

Application of Stack in Data Structures

In this article, we will discuss all the different applications of stack. What is meant by stack? The stack is a non-primitive linear data structure in which the insertion of the new...

11 minutes read.

Data Structure Infix to Prefix Conversion

Infix to Prefix Conversion In present time, we use the infix expression in our daily life but the computers are not able to understand this format because they need to keep...

4 minutes read.

Perfect Binary Tree

Complete binary trees are an important and general topic in the concept – of tree data structures. Before discussing a complete binary tree, we need to know the concept of...

4 minutes read.

Red Black Tree

Red Black Tree A red-black tree is referred as self-balancing binary search tree. The tree was invented by Rudolf Bayer in 1972. In red-black, each node stores an extra bit that...

8 minutes read.