×

Binary tree insertion

As we all know, a binary tree has a maximum of two children and helps us manage the info correctly. Here the name of the tree itself portrays the mechanism and tells us that each of the nodes present in the tree can either have zero, one or two child nodes maximum and not more than that. There is another set of trees called the binary search tree, which is a successor of the binary tree and holds all the modifications plus one application required to perform the operations. Several properties need to be obeyed when forming a binary tree, but we will not discuss them in this article; this article is solely for the implementation and practice of the insertion operation in the binary tree.

Insertion operation is solely based on creating a new space in the existing binary tree to add a new element into the tree while maintaining the properties and balance of the binary tree intact.

Given there is a node where we have to insert a specific node in the binary tree and adjust the tree. In the next section, we will see the implementation and working of the same and understand it more vividly.

Implementation

#include <iostream>
#include <queue>
using namespace std;


/* A binary tree node has info, a pointer to the lft child
and a pointer to the rt child */


struct Node {
	int info;
	Node* lft;
	Node* rt;
};


// Function to create a new node
Node* CreateNode(int info)
{
	Node* newNode = new Node();
	if (!newNode) {
		cout << "Memory error\n";
		return NILL;
	}
	newNode->info = info;
	newNode->lft = newNode->rt = NILL;
	return newNode;
}


// Function to insert an element in the binary tree
Node* InsertNode(Node* root, int info)
{
	// If the tree is empty, assign a new node address to the root
	if (root == NILL) {
		root = CreateNode(info);
		return root;
	}


	// Else, do level order traversal until we find an empty
	// place, i.e. either lft child or rt child of some
	// node is pointing to NILL.
	queue<Node*> q;
	m.push(root);


	while (!m.empty()) {
		Node* temp = m.forefront();
		m.pop();


		if (temp->lft != NILL)
			m.push(temp->lft);
		else {
			temp->lft = CreateNode(info);
			return root;
		}


		if (temp->rt != NILL)
			m.push(temp->rt);
		else {
			temp->rt = CreateNode(info);
			return root;
		}
	}
}


/* In order traversal of a binary tree */


void inorder(Node* temp)
{
	if (temp == NILL)
		return;


	inorder(temp->lft);
	cout << temp->info << ' ';
	inorder(temp->rt);
}


// Driver code
int main()
{
	Node* root = CreateNode(10);
	root->lft = CreateNode(11);
	root->lft->lft = CreateNode(7);
	root->rt = CreateNode(9);
	root->rt->lft = CreateNode(15);
	root->rt->rt = CreateNode(8);


	cout << "Inorder traversal before insertion: ";
	inorder(root);
	cout << endl;


	int key = 12;
	root = InsertNode(root, key);


	cout << "Inorder traversal after insertion: ";
	inorder(root);
	cout << endl;


	return 0;
}

Output:

Binary tree insertion

Example2)

#include<iostream>
#include<queue>
using namespace std;


struct node {
    int info;
    struct node *lft, *rt;
};


/* Function to insert new nodes to the tree. */
struct node *new node(int info) {
    struct node *node;
    node = (struct node*)malloc(sizeof(struct node));
    node->info = info;
    node->lft = NILL;
    node->rt = NILL;
    return node;
}


/*Creating a function that will help us to form new nodes in the tree when an existing node doesn’t contain any left or right child. */
void insert(struct node *root, int info) {
    struct node *temp;
    queue<struct node*>m;
    m.push(root);
    while(!m.empty()) 
    {
        temp = m.forefront();
        m.pop();


        /* Now, we will push a new node to the left of the existing node.*/
        if(temp->lft == NILL) {
            temp->lft = new nod(info);
            br;
        }


        /* if the node present on the left is not empty or vacant, then we have to push it to the queue.*/
        else
            m.push(temp->lft);
        
        /* Now, we will push a new node to the right of the existing node.*/
        if(temp->rt == NILL) {
            temp->rt = new nod(info);
            br;
        }


        /* if the node present in the right is not empty or vacant, then we have to push it to the queue.*/
        else
            m.push(temp->rt);
    }
}


/* WE are writing a function that will traverse each node in the tree.*/
void traversal(struct nod *root) {
    if(root == NILL)
        return;
    traversal(root->lft);
    cout << root->info << " ";
    traversal(root->rt);
}


/* Driver function to check the above algorithm. */
int main() {
    struct node* root = new node(1);
    root->lft = new node(10);
    root->lft->lft = new node(20);
    root->rt = new node(34);
    int key = 12;
    insert(root, key);
    cout << endl;
    cout << "Inorder traversal after insertion: ";
    traversal(root);
}

Output:

Binary tree insertion

Related Topics

Introduction to 2D-Arrays

Two Dimensional Array Technical Definitions An array of arrays is a common definition for a two-dimensional array. A matrix is another name for a two-dimensional array. A matrix looks like a table...

3 minutes read.

Big O Notations

What is Big O Notation, and why is it important? "Big O notation is a mathematical notation that depicts a function's limiting behaviour when the input tends towards a certain value...

10 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.

Adding one to the number represented an array of digits

You have given one array, which consists of values which represent the different digits of a number. You have to add 1 to this number and store the result in...

3 minutes read.

Recursion in Fibonacci

Fibonacci heap is considered to be a particular execution of the heap data structure that ultimately helps in making use of not just any number but the Fibonacci numbers. It...

3 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.

Binary search tree traversal in-order pre-order post-order examples

A binary search tree is a type of non-linear tree in which the tree contains at least two nods. It is called binary because of its nature that states bi...

8 minutes read.

Shell Sort

Shell Sort: Shell sort is a sorting algorithm. It is an extended version of the insertion sort. In this sorting, we compare the elements that are distant apart rather than the...

5 minutes read.

Priority Queue in Data Structure

Priority Queue A priority queue is a special kind of queue, in priority queue we give some priority to an element and according to this priority an element can be served...

3 minutes read.

Reverse a Linked List in groups of given size

Reverse a Linked List in groups of given size This article will explain how to reverse a linked list in groups of given size. Here we have given a linked list...

2 minutes read.

Bubble Sort vs Quick Sort

In this article, we are going to compare two sorting techniques, Bubble sort and Quick Sort. In starting, we will first discuss the idea of sorting an array using bubble...

7 minutes read.

Cocktail Sort

C Program executes cocktail sort. Combo sort is a somewhat straightforward arranging calculation initially planned by Wlodzimierz Dobosiewicz and Artur Borowy in 1980, later rediscovered by Stephen Lacey and Richard Box...

5 minutes read.

Given a Generate all Structurally Unique Binary Search Trees

Implementation // Creating a C++ program that will help us build all the binary search trees for the keys from 1 to n.  #include <bits/stdc++.h> using namespace std; // creating a structure that will...

8 minutes read.

What are the types of Trees in Data Structure

Data structures Data management is called database management. This allows the computer to sort or organize the data for efficient retrieval. A data model is a system used to store, manage,...

6 minutes read.

AVL Tree

AVL Tree AVL Tree is referred to as self-balanced or height-balanced binary search tree where the difference between heights of its left subtree and right subtree (Balance Factor) can't more than...

25 minutes read.

Singly Linked list

Singly Linked list A singly linked list is a kind of linked list which is unidirectional. If we talk about singly linked list, then we can say it can be traversed...

3 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.

Semi-Structured data

In this article, we will discuss the semi-structured data. Data can be defined as the distinct piece of information that is gathered and translated for some purpose. It can be...

5 minutes read.

Linked List Data Structure

Linked list in DS: The linked list is a non-primitive and linear data structure. It is a list of a particular type of data element that is connected to each...

3 minutes read.

Arrange consonants and vowels nodes in a linked list

Arrange consonants and vowels nodes in a linked list In this problem, we have given a singly linked list. Here we will arrange the consonants and vowels nodes of the list...

2 minutes read.