×

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

Insertion Sort in Data Structures

Insertion Sort in C++ Insertion sort is a sorting algorithm that, in each iteration, installs an unsorted element in its proper position Insertion sort operates in a similar way to how we...

3 minutes read.

Convert binary tree to a doubly linked list

Implementation //creating a C++ program for the transition of a binary tree into a linked list. #include <iostream> using namespace std; /* Firstly, let’s create a binary tree that will help us in setting...

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

What is a Tree in Terms of a Graph?

To know the explanation of trees in terms of graphs, we need first to know what trees and graphs are. So let us first learn about trees and graphs. Trees and...

6 minutes read.

Circular Linked List

Circular Linked List A circular linked list where all nodes are connected to their next node and last node is connected to the starting node or we can say all nodes...

5 minutes read.

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

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

Identical Linked Lists

Identical Linked Lists In this problem, we have given two linked lists, and we need to check whether the given linked lists are identical or not. Identical means they have the...

4 minutes read.

Delete nodes from the linked list which have a greater value on the right side

Delete nodes from the linked list which have a greater value on the right side In this problem, we have given a singly linked list, and we need to remove all...

3 minutes read.

Given a Binary Tree Check the Zig-Zag Traversal

Implementation // The C++ implementation of the zig-zag traversal method in the O(n) time.  #include <iostream> #include <stack> using namespace std; // creating a binary tree node. struct __nod { int record; struct __nod *Lft, *Rt; }; // creating a...

4 minutes read.

Given a Binary Tree, Check if it's balanced

Implementation /*Creating a C++ program that will help us identify whether the given tree is height-balanced or not.  */ #include <bits/stdc++.h> using namespace std; /* A particular binary tree node consists of data with some...

4 minutes read.

FLEX (Fast Lexical Analyzer Generator)

FLEX stands for Fast Lexical Analyzer Generator. Around 1987, Vern Paxson created Flex in C with a great deal of input and inspiration from Van Jacobson. Van Jacobson's approach is...

3 minutes read.

Union and Intersection of two Linked Lists

Union and Intersection of two Linked Lists This article explains how we can do the union and intersection of two linked lists. In this problem, we have given two linked lists...

3 minutes read.

What is the Use of Segment Trees in Data Structure?

Segment trees Segment trees are also called statistical trees in computer science. They are a type of tree data structure. Segment trees are used to store information regarding segments and intervals....

6 minutes read.

Threaded Binary Trees

Introduction Threaded Binary Trees (TBTs) are an enhancement of normal binary trees intended for in-order traversal only. This means that this data structure is developed with the objective of making the...

12 minutes read.

Advantages and Disadvantages of Linked List

Advantages of Linked List The linked list is a dynamic data structure.You can also decrease and increase the linked list at run-time. That is, you can allocate and deallocate memory at...

3 minutes read.

Traversal of binary tree

Traversal of binary tree: A node is visited only once in the traversal of the binary tree. There are three main types of traversal methods in the binary tree. In-order traversalPre-order...

3 minutes read.

Difference between B-tree and Binary Tree

What is B-TREE? The nodes of B-tree are sorted during in-order traversal, and it is called self-balancing tree. A node in a B-tree can have more than two offspring, in contrast...

3 minutes read.

What is an AVL Tree in Data Structure?

AVL tree stands for (Adelson, Velskii, & Landis Tree) Data structure Data management is called database management. A data model is a system used to store, manage, and optimize computer resources. Data...

4 minutes read.

Introduction to Arrays

What exactly is an array? A group of related data pieces stored in contiguous memory regions is referred to as an array. It is the most basic data structure in which...

5 minutes read.