Data Structures Tutorial

Data Structures Tutorial Asymptotic Notation Structure and Union Array Data Structure Linked list Data Structure Type of Linked list Advantages and Disadvantages of linked list Queue Data Structure Implementation of Queue Stack Data Structure Implementation of Stack Sorting Insertion sort Quick sort Selection sort Heap sort Merge sort Bucket sort Count sort Radix sort Shell sort Tree Traversal of the binary tree Binary search tree Graph Spanning tree Linear Search Binary Search Hashing Collision Resolution Techniques

Misc Topic:

Priority Queue in Data Structure Deque in Data Structure Difference Between Linear And Non Linear Data Structures Queue Operations In Data Structure About Data Structures Data Structures Algorithms Types of Data Structures Big O Notations Introduction to Arrays Introduction to 1D-Arrays Operations on 1D-Arrays Introduction to 2D-Arrays Operations on 2D-Arrays Strings in Data Structures String Operations Application of 2D array Bubble Sort Insertion Sort Sorting Algorithms What is DFS Algorithm What Is Graph Data Structure What is the difference between Tree and Graph What is the difference between DFS and BFS Bucket Sort Dijkstra’s vs Bellman-Ford Algorithm Linear Queue Data Structure in C Stack Using Array Stack Using Linked List Recursion in Fibonacci Stack vs Array What is Skewed Binary Tree Primitive Data Structure in C Dynamic memory allocation of structure in C Application of Stack in Data Structures Binary Tree in Data Structures Heap Data Structure Recursion - Factorial and Fibonacci What is B tree what is B+ tree Huffman tree in Data Structures Insertion Sort vs Bubble Sort Adding one to the number represented an array of digits Bitwise Operators and their Important Tricks Blowfish algorithm Bubble Sort vs Selection Sort Hashing and its Applications Heap Sort vs Merge Sort Insertion Sort vs Selection Sort Merge Conflicts and ways to handle them Difference between Stack and Queue AVL tree in data structure c++ Bubble sort algorithm using Javascript Buffer overflow attack with examples Find out the area between two concentric circles Lowest common ancestor in a binary search tree Number of visible boxes putting one inside another Program to calculate the area of the circumcircle of an equilateral triangle Red-black Tree in Data Structures Strictly binary tree in Data Structures 2-3 Trees and Basic Operations on them Asynchronous advantage actor-critic (A3C) Algorithm Bubble Sort vs Heap Sort Digital Search Tree in Data Structures Minimum Spanning Tree Permutation Sort or Bogo Sort Quick Sort vs Merge Sort Boruvkas algorithm Bubble Sort vs Quick Sort Common Operations on various Data Structures Detect and Remove Loop in a Linked List How to Start Learning DSA Print kth least significant bit number Why is Binary Heap Preferred over BST for Priority Queue Bin Packing Problem Binary Tree Inorder Traversal Burning binary tree Equal Sum What is a Threaded Binary Tree? What is a full Binary Tree? Bubble Sort vs Merge Sort B+ Tree Program in Q language Deletion Operation from A B Tree Deletion Operation of the binary search tree in C++ language Does Overloading Work with Inheritance Balanced Binary Tree Binary tree deletion Binary tree insertion Cocktail Sort Comb Sort FIFO approach Operations of B Tree in C++ Language Recaman’s Sequence Tim Sort Understanding Data Processing Applications of trees in data structures Binary Tree Implementation Using Arrays Convert a Binary Tree into a Binary Search Tree Create a binary search tree Horizontal and Vertical Scaling Invert binary tree LCA of binary tree Linked List Representation of Binary Tree Optimal binary search tree in DSA Serialize and Deserialize a Binary Tree Tree terminology in Data structures Vertical Order Traversal of Binary Tree What is a Height-Balanced Tree in Data Structure Convert binary tree to a doubly linked list Fundamental of Algorithms Introduction and Implementation of Bloom Filter Optimal binary search tree using dynamic programming Right side view of binary tree Symmetric binary tree Trim a binary search tree What is a Sparse Matrix in Data Structure What is a Tree in Terms of a Graph What is the Use of Segment Trees in Data Structure What Should We Learn First Trees or Graphs in Data Structures All About Minimum Cost Spanning Trees in Data Structure Convert Binary Tree into a Threaded Binary Tree Difference between Structured and Object-Oriented Analysis FLEX (Fast Lexical Analyzer Generator) Object-Oriented Analysis and Design Sum of Nodes in a Binary Tree What are the types of Trees in Data Structure What is a 2-3 Tree in Data Structure What is a Spanning Tree in Data Structure What is an AVL Tree in Data Structure Given a Binary Tree, Check if it's balanced

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



ADVERTISEMENT
ADVERTISEMENT