The Wayback Machine - https://web.archive.org/web/20240819224309/https://www.geeksforgeeks.org/threaded-binary-tree-insertion/
Open In App

Threaded Binary Tree | Insertion

Last Updated : 14 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

We have already discuss the Binary Threaded Binary Tree.
Insertion in Binary threaded tree is similar to insertion in binary tree but we will have to adjust the threads after insertion of each element.

C representation of Binary Threaded Node: 

struct Node
{
  struct Node *left, *right;
  int info;

  // false if left pointer points to predecessor 
  // in Inorder Traversal
  boolean lthread; 

  // false if right pointer points to successor 
  // in Inorder Traversal
  boolean rthread; 
};

In the following explanation, we have considered Binary Search Tree (BST) for insertion as insertion is defined by some rules in BSTs.
Let tmp be the newly inserted node. There can be three cases during insertion:

Case 1: Insertion in empty tree 

Both left and right pointers of tmp will be set to NULL and new node becomes the root. 

root = tmp;
tmp -> left = NULL;
tmp -> right = NULL;

Case 2: When new node inserted as the left child 

After inserting the node at its proper place we have to make its left and right threads points to inorder predecessor and successor respectively. The node which was inorder successor. So the left and right threads of the new node will be- 

tmp -> left = par ->left;
tmp -> right = par;

Before insertion, the left pointer of parent was a thread, but after insertion it will be a link pointing to the new node. 

par -> lthread = false;
par -> left = temp;

Following example show a node being inserted as left child of its parent. 
 

After insertion of 13, 
 

Predecessor of 14 becomes the predecessor of 13, so left thread of 13 points to 10. 
Successor of 13 is 14, so right thread of 13 points to left child which is 13. 
Left pointer of 14 is not a thread now, it points to left child which is 13.

Case 3: When new node is inserted as the right child 

The parent of tmp is its inorder predecessor. The node which was inorder successor of the parent is now the inorder successor of this node tmp. So the left and right threads of the new node will be- 

tmp -> left = par;
tmp -> right = par -> right;

Before insertion, the right pointer of parent was a thread, but after insertion it will be a link pointing to the new node. 

par -> rthread = false;
par -> right = tmp;

Following example shows a node being inserted as right child of its parent. 
 

After 15 inserted, 
 

Successor of 14 becomes the successor of 15, so right thread of 15 points to 16 
Predecessor of 15 is 14, so left thread of 15 points to 14. 
Right pointer of 14 is not a thread now, it points to right child which is 15.

C++ implementation to insert a new node in Threaded Binary Search Tree: 
Like standard BST insert, we search for the key value in the tree. If key is already present, then we return otherwise the new key is inserted at the point where search terminates. In BST, search terminates either when we find the key or when we reach a NULL left or right pointer. Here all left and right NULL pointers are replaced by threads except left pointer of first node and right pointer of last node. So here search will be unsuccessful when we reach a NULL pointer or a thread.

Implementation:

C++




// Insertion in Threaded Binary Search Tree.
#include<bits/stdc++.h>
using namespace std;
  
struct Node
{
    struct Node *left, *right;
    int info;
  
    // False if left pointer points to predecessor
    // in Inorder Traversal
    bool lthread;
  
    // False if right pointer points to successor
    // in Inorder Traversal
    bool rthread;
};
  
// Insert a Node in Binary Threaded Tree
struct Node *insert(struct Node *root, int ikey)
{
    // Searching for a Node with given value
    Node *ptr = root;
    Node *par = NULL; // Parent of key to be inserted
    while (ptr != NULL)
    {
        // If key already exists, return
        if (ikey == (ptr->info))
        {
            printf("Duplicate Key !\n");
            return root;
        }
  
        par = ptr; // Update parent pointer
  
        // Moving on left subtree.
        if (ikey < ptr->info)
        {
            if (ptr -> lthread == false)
                ptr = ptr -> left;
            else
                break;
        }
  
        // Moving on right subtree.
        else
        {
            if (ptr->rthread == false)
                ptr = ptr -> right;
            else
                break;
        }
    }
  
    // Create a new node
    Node *tmp = new Node;
    tmp -> info = ikey;
    tmp -> lthread = true;
    tmp -> rthread = true;
  
    if (par == NULL)
    {
        root = tmp;
        tmp -> left = NULL;
        tmp -> right = NULL;
    }
    else if (ikey < (par -> info))
    {
        tmp -> left = par -> left;
        tmp -> right = par;
        par -> lthread = false;
        par -> left = tmp;
    }
    else
    {
        tmp -> left = par;
        tmp -> right = par -> right;
        par -> rthread = false;
        par -> right = tmp;
    }
  
    return root;
}
  
// Returns inorder successor using rthread
struct Node *inorderSuccessor(struct Node *ptr)
{
    // If rthread is set, we can quickly find
    if (ptr -> rthread == true)
        return ptr->right;
  
    // Else return leftmost child of right subtree
    ptr = ptr -> right;
    while (ptr -> lthread == false)
        ptr = ptr -> left;
    return ptr;
}
  
// Printing the threaded tree
void inorder(struct Node *root)
{
    if (root == NULL)
        printf("Tree is empty");
  
    // Reach leftmost node
    struct Node *ptr = root;
    while (ptr -> lthread == false)
        ptr = ptr -> left;
  
    // One by one print successors
    while (ptr != NULL)
    {
        printf("%d ",ptr -> info);
        ptr = inorderSuccessor(ptr);
    }
}
  
// Driver Program
int main()
{
    struct Node *root = NULL;
  
    root = insert(root, 20);
    root = insert(root, 10);
    root = insert(root, 30);
    root = insert(root, 5);
    root = insert(root, 16);
    root = insert(root, 14);
    root = insert(root, 17);
    root = insert(root, 13);
  
    inorder(root);
  
    return 0;
}


Java




// Java program Insertion in Threaded Binary Search Tree. 
import java.util.*;
public class solution
{
static class Node 
{ 
     Node left, right; 
    int info; 
    
    // False if left pointer points to predecessor 
    // in Inorder Traversal 
    boolean lthread; 
    
    // False if right pointer points to successor 
    // in Inorder Traversal 
    boolean rthread; 
}; 
    
// Insert a Node in Binary Threaded Tree 
static Node insert( Node root, int ikey) 
{ 
    // Searching for a Node with given value 
    Node ptr = root; 
    Node par = null; // Parent of key to be inserted 
    while (ptr != null) 
    { 
        // If key already exists, return 
        if (ikey == (ptr.info)) 
        { 
            System.out.printf("Duplicate Key !\n"); 
            return root; 
        } 
    
        par = ptr; // Update parent pointer 
    
        // Moving on left subtree. 
        if (ikey < ptr.info) 
        { 
            if (ptr . lthread == false) 
                ptr = ptr . left; 
            else
                break; 
        } 
    
        // Moving on right subtree. 
        else
        { 
            if (ptr.rthread == false) 
                ptr = ptr . right; 
            else
                break; 
        } 
    } 
    
    // Create a new node 
    Node tmp = new Node(); 
    tmp . info = ikey; 
    tmp . lthread = true; 
    tmp . rthread = true; 
      
    if (par == null) 
    { 
        root = tmp; 
        tmp . left = null; 
        tmp . right = null; 
    } 
    else if (ikey < (par . info)) 
    { 
        tmp . left = par . left; 
        tmp . right = par; 
        par . lthread = false; 
        par . left = tmp; 
    } 
    else
    { 
        tmp . left = par; 
        tmp . right = par . right; 
        par . rthread = false; 
        par . right = tmp; 
    } 
    
    return root; 
} 
    
// Returns inorder successor using rthread 
static  Node inorderSuccessor( Node ptr) 
{ 
    // If rthread is set, we can quickly find 
    if (ptr . rthread == true) 
        return ptr.right; 
    
    // Else return leftmost child of right subtree 
    ptr = ptr . right; 
    while (ptr . lthread == false) 
        ptr = ptr . left; 
    return ptr; 
} 
    
// Printing the threaded tree 
static void inorder( Node root) 
{ 
    if (root == null) 
        System.out.printf("Tree is empty"); 
    
    // Reach leftmost node 
     Node ptr = root; 
    while (ptr . lthread == false) 
        ptr = ptr . left; 
    
    // One by one print successors 
    while (ptr != null) 
    { 
        System.out.printf("%d ",ptr . info); 
        ptr = inorderSuccessor(ptr); 
    } 
} 
    
// Driver Program 
public static void main(String[] args)
{ 
     Node root = null; 
    
    root = insert(root, 20); 
    root = insert(root, 10); 
    root = insert(root, 30); 
    root = insert(root, 5); 
    root = insert(root, 16); 
    root = insert(root, 14); 
    root = insert(root, 17); 
    root = insert(root, 13); 
    
    inorder(root); 
}  
}
//contributed by Arnab Kundu
  
// This code is updated By Susobhan Akhuli


Python3




# Insertion in Threaded Binary Search Tree. 
class newNode:
    def __init__(self, key):
      
        # False if left pointer points to 
        # predecessor in Inorder Traversal 
        self.info = key
        self.left = None
        self.right =None
        self.lthread = True
      
        # False if right pointer points to 
        # successor in Inorder Traversal 
        self.rthread = True
  
# Insert a Node in Binary Threaded Tree 
def insert(root, ikey):
      
    # Searching for a Node with given value 
    ptr = root 
    par = None # Parent of key to be inserted 
    while ptr != None:
          
        # If key already exists, return 
        if ikey == (ptr.info):
            print("Duplicate Key !") 
            return root 
  
        par = ptr # Update parent pointer 
  
        # Moving on left subtree. 
        if ikey < ptr.info:
            if ptr.lthread == False: 
                ptr = ptr.left 
            else:
                break
  
        # Moving on right subtree. 
        else:
            if ptr.rthread == False: 
                ptr = ptr.right 
            else:
                break
  
    # Create a new node 
    tmp = newNode(ikey) 
  
    if par == None:
        root = tmp 
        tmp.left = None
        tmp.right = None
    elif ikey < (par.info):
        tmp.left = par.left 
        tmp.right = par 
        par.lthread = False
        par.left = tmp
    else:
        tmp.left = par 
        tmp.right = par.right 
        par.rthread = False
        par.right = tmp
  
    return root
  
# Returns inorder successor using rthread 
def inorderSuccessor(ptr):
      
    # If rthread is set, we can quickly find 
    if ptr.rthread == True: 
        return ptr.right 
  
    # Else return leftmost child of 
    # right subtree 
    ptr = ptr.right 
    while ptr.lthread == False: 
        ptr = ptr.left 
    return ptr
  
# Printing the threaded tree 
def inorder(root):
    if root == None: 
        print("Tree is empty") 
  
    # Reach leftmost node 
    ptr = root 
    while ptr.lthread == False: 
        ptr = ptr.left 
  
    # One by one print successors 
    while ptr != None:
        print(ptr.info,end=" ") 
        ptr = inorderSuccessor(ptr)
  
# Driver Code
if __name__ == '__main__':
    root = None
  
    root = insert(root, 20) 
    root = insert(root, 10) 
    root = insert(root, 30) 
    root = insert(root, 5) 
    root = insert(root, 16) 
    root = insert(root, 14) 
    root = insert(root, 17) 
    root = insert(root, 13) 
  
    inorder(root) 
      
# This code is contributed by PranchalK


C#




using System;
  
// C# program Insertion in Threaded Binary Search Tree.  
public class solution
{
public class Node
{
     public Node left, right;
    public int info;
  
    // False if left pointer points to predecessor  
    // in Inorder Traversal  
    public bool lthread;
  
    // False if right pointer points to successor  
    // in Inorder Traversal  
    public bool rthread;
}
  
// Insert a Node in Binary Threaded Tree  
public static Node insert(Node root, int ikey)
{
    // Searching for a Node with given value  
    Node ptr = root;
    Node par = null; // Parent of key to be inserted
    while (ptr != null)
    {
        // If key already exists, return  
        if (ikey == (ptr.info))
        {
            Console.Write("Duplicate Key !\n");
            return root;
        }
  
        par = ptr; // Update parent pointer
  
        // Moving on left subtree.  
        if (ikey < ptr.info)
        {
            if (ptr.lthread == false)
            {
                ptr = ptr.left;
            }
            else
            {
                break;
            }
        }
  
        // Moving on right subtree.  
        else
        {
            if (ptr.rthread == false)
            {
                ptr = ptr.right;
            }
            else
            {
                break;
            }
        }
    }
  
    // Create a new node  
    Node tmp = new Node();
    tmp.info = ikey;
    tmp.lthread = true;
    tmp.rthread = true;
  
    if (par == null)
    {
        root = tmp;
        tmp.left = null;
        tmp.right = null;
    }
    else if (ikey < (par.info))
    {
        tmp.left = par.left;
        tmp.right = par;
        par.lthread = false;
        par.left = tmp;
    }
    else
    {
        tmp.left = par;
        tmp.right = par.right;
        par.rthread = false;
        par.right = tmp;
    }
  
    return root;
}
  
// Returns inorder successor using rthread  
public static Node inorderSuccessor(Node ptr)
{
    // If rthread is set, we can quickly find  
    if (ptr.rthread == true)
    {
        return ptr.right;
    }
  
    // Else return leftmost child of right subtree  
    ptr = ptr.right;
    while (ptr.lthread == false)
    {
        ptr = ptr.left;
    }
    return ptr;
}
  
// Printing the threaded tree  
public static void inorder(Node root)
{
    if (root == null)
    {
        Console.Write("Tree is empty");
    }
  
    // Reach leftmost node  
     Node ptr = root;
    while (ptr.lthread == false)
    {
        ptr = ptr.left;
    }
  
    // One by one print successors  
    while (ptr != null)
    {
        Console.Write("{0:D} ",ptr.info);
        ptr = inorderSuccessor(ptr);
    }
}
  
// Driver Program  
public static void Main(string[] args)
{
     Node root = null;
  
    root = insert(root, 20);
    root = insert(root, 10);
    root = insert(root, 30);
    root = insert(root, 5);
    root = insert(root, 16);
    root = insert(root, 14);
    root = insert(root, 17);
    root = insert(root, 13);
  
    inorder(root);
}
}
  
  // This code is contributed by Shrikant13


Javascript




<script>
// javascript program Insertion in Threaded Binary Search Tree. 
     class Node {
     constructor(){
this.left = null, this.right = null;
        this.info = 0;
  
        // False if left pointer points to predecessor
        // in Inorder Traversal
        this.lthread = false;
  
        // False if right pointer points to successor
        // in Inorder Traversal
        this.rthread = false;
    }
    }
  
    // Insert a Node in Binary Threaded Tree
    function insert(root , ikey) {
        // Searching for a Node with given value
var ptr = root;
var par = null; // Parent of key to be inserted
        while (ptr != null) {
            // If key already exists, return
            if (ikey == (ptr.info)) {
                document.write("Duplicate Key !\n");
                return root;
            }
  
            par = ptr; // Update parent pointer
  
            // Moving on left subtree.
            if (ikey < ptr.info) {
                if (ptr.lthread == false)
                    ptr = ptr.left;
                else
                    break;
            }
  
            // Moving on right subtree.
            else {
                if (ptr.rthread == false)
                    ptr = ptr.right;
                else
                    break;
            }
        }
  
        // Create a new node
var tmp = new Node();
        tmp.info = ikey;
        tmp.lthread = true;
        tmp.rthread = true;
  
        if (par == null) {
            root = tmp;
            tmp.left = null;
            tmp.right = null;
        } else if (ikey < (par.info)) {
            tmp.left = par.left;
            tmp.right = par;
            par.lthread = false;
            par.left = tmp;
        } else {
            tmp.left = par;
            tmp.right = par.right;
            par.rthread = false;
            par.right = tmp;
        }
  
        return root;
    }
  
    // Returns inorder successor using rthread
    function inorderSuccessor(ptr) {
        // If rthread is set, we can quickly find
        if (ptr.rthread == true)
            return ptr.right;
  
        // Else return leftmost child of right subtree
        ptr = ptr.right;
        while (ptr.lthread == false)
            ptr = ptr.left;
        return ptr;
    }
  
    // Printing the threaded tree
    function inorder(root) {
        if (root == null)
            document.write("Tree is empty");
  
        // Reach leftmost node
var ptr = root;
        while (ptr.lthread == false)
            ptr = ptr.left;
  
        // One by one print successors
        while (ptr != null) {
            document.write(ptr.info+" ");
            ptr = inorderSuccessor(ptr);
        }
    }
  
    // Driver Program
      
var root = null;
  
        root = insert(root, 20);
        root = insert(root, 10);
        root = insert(root, 30);
        root = insert(root, 5);
        root = insert(root, 16);
        root = insert(root, 14);
        root = insert(root, 17);
        root = insert(root, 13);
  
        inorder(root);
  
// This code contributed by aashish1995
</script>


Output

5 10 13 14 16 17 20 30 

Time Complexity: O(log N)

Space Complexity: O(1), since no extra space used.

 



Similar Reads

Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
We have discussed Threaded Binary Tree. The idea of threaded binary trees is to make inorder traversal faster and do it without stack and without recursion. In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Wherever a right pointer is NULL, it is used to store inorder successor. The following diagram sho
12 min read
Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
Idea of Threaded Binary Tree is to make inorder traversal faster and do it without stack and without recursion. In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Wherever a right pointer is NULL, it is used to store inorder successor. Following diagram shows an example Single Threaded Binary Tree. The do
12 min read
Reverse Morris traversal using Threaded Binary Tree
What is Morris traversal?Morris (InOrder) Traversal is a tree traversal algorithm that does not use recursion or stacks. This traversal creates links as descendants and outputs nodes using those links. Finally, undo the changes to restore the original tree.Given a binary tree, task is to do reverse inorder traversal using Morris Traversal. Prerequi
10 min read
Double Threaded Binary Search Tree
Double Threaded Binary Search Tree: is a binary search tree in which the nodes are not every left NULL pointer points to its inorder predecessor and the right NULL pointer points to the inorder successor.The threads are also useful for fast accessing the ancestors of a node.  Double Threaded Binary Search Tree is one of the most used types of Advan
15+ min read
Inorder Non-threaded Binary Tree Traversal without Recursion or Stack
We have discussed Thread based Morris Traversal. Can we do inorder traversal without threads if we have parent pointers available to us? Input: Root of Below Tree [Every node of tree has parent pointer also] 10 / \ 5 100 / \ 80 120 Output: 5 10 80 100 120 The code should not extra space (No Recursion and stack) In inorder traversal, we follow "left
11 min read
Threaded Binary Search Tree | Deletion
A threaded binary tree node looks like following. C/C++ Code struct Node { struct Node *left, *right; int info; // false if left pointer points to predecessor // in Inorder Traversal bool lthread; // false if right pointer points to predecessor // in Inorder Traversal bool rthread; }; Java Code static class Node { Node left, right; int info; // Tru
15+ min read
Threaded Binary Tree
Inorder traversal of a Binary tree can either be done using recursion or with the use of a auxiliary stack. The idea of threaded binary trees is to make inorder traversal faster and do it without stack and without recursion. A binary tree is made threaded by making all right child pointers that would normally be NULL point to the inorder successor
10 min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Convert a Binary Tree into its Mirror Tree (Invert Binary Tree)
Given a binary tree, the task is to convert the binary tree into its Mirror tree. Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes interchanged. Recommended PracticeMirror TreeTry It!The idea is to traverse recursively and swap the right and left subtrees after traversing the subtrees. Follow
15+ min read
Insertion in a Binary Tree in level order
Given a binary tree and a key, insert the key into the binary tree at the first position available in level order. The idea is to do an iterative level order traversal of the given tree using queue. If we find a node whose left child is empty, we make a new key as the left child of the node. Else if we find a node whose right child is empty, we mak
7 min read
Insertion in Binary Search Tree (BST)
Given a BST, the task is to insert a new node in this BST. Example: How to Insert a value in a Binary Search Tree:A new key is always inserted at the leaf by maintaining the property of the binary search tree. We start searching for a key from the root until we hit a leaf node. Once a leaf node is found, the new node is added as a child of the leaf
15 min read
Convert a Generic Tree(N-array Tree) to Binary Tree
Prerequisite: Generic Trees(N-array Trees) In this article, we will discuss the conversion of the Generic Tree to a Binary Tree. Following are the rules to convert a Generic(N-array Tree) to a Binary Tree: The root of the Binary Tree is the Root of the Generic Tree.The left child of a node in the Generic Tree is the Left child of that node in the B
13 min read
Check whether a binary tree is a full binary tree or not | Iterative Approach
Given a binary tree containing n nodes. The problem is to check whether the given binary tree is a full binary tree or not. A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has only one child node. Examples: Input : 1 / \ 2 3 / \ 4 5 Outp
8 min read
Binary Tree to Binary Search Tree Conversion using STL set
Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of the Binary Tree.This solution will use Sets of C++ STL instead of array-based solution. Examples: Example 1 Input: 10 / \ 2 7 / \ 8 4 Output: 8 / \ 4 10 / \ 2 7 Example 2 Input: 10 / \ 30 15 / \ 20 5 Output: 15 / \
12 min read
Check whether a given binary tree is skewed binary tree or not?
Given a Binary Tree check whether it is skewed binary tree or not. A skewed tree is a tree where each node has only one child node or none. Examples: Input : 5 / 4 \ 3 / 2 Output : Yes Input : 5 / 4 \ 3 / \ 2 4 Output : No The idea is to check if a node has two children. If node has two children return false, else recursively compute whether subtre
13 min read
Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
Given two binary trees S and T, the task is the check that if S is a subtree of the Tree T. For Example: Input: Tree T - 1 / \ 2 3 / \ / \ 4 5 6 7 Tree S - 2 / \ 4 5 Output: YES Explanation: The above tree is the subtree of the tree T, Hence the output is YES Approach: The idea is to traverse both the tree in Pre-order Traversal and check for each
11 min read
Check if a Binary tree is Subtree of another Binary tree | Set 3
Given two binary trees, check if the first tree is a subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree. Examples: Input: Tree-T Tree-S 1 3 / \ / 2
15 min read
Check whether a binary tree is a full binary tree or not
A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has one child node. More information about full binary trees can be found here. For Example : Recommended PracticeFull binary treeTry It! To check whether a binary tree is a full binary tre
14 min read
Check if a binary tree is subtree of another binary tree | Set 2
Given two binary trees, check if the first tree is a subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree.For example, in the following case, Tree1 i
15+ min read
Minimum swap required to convert binary tree to binary search tree
Given the array representation of Complete Binary Tree i.e, if index i is the parent, index 2*i + 1 is the left child and index 2*i + 2 is the right child. The task is to find the minimum number of swap required to convert it into Binary Search Tree. Examples: Input : arr[] = { 5, 6, 7, 8, 9, 10, 11 } Output : 3 Binary tree of the given array: Swap
8 min read
Difference between Binary Tree and Binary Search Tree
Binary Tree Data Structure:A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right children.  Binary Search Tree Data Structure (BST):A binary search tree is a hierarchical data structure where each node has at most two children, w
2 min read
Binary Tree to Binary Search Tree Conversion
Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of Binary Tree. Examples Example 1Input: 10 / \ 2 7 / \ 8 4Output: 8 / \ 4 10 / \ 2 7Example 2Input: 10 / \ 30 15 / \ 20 5Output: 15 / \ 10 20 / \ 5 30Solution: Following is a 3 step solution for converting Binary tre
15+ min read
Check if a Binary Tree is subtree of another binary tree | Set 1
Given two binary trees, check if the first tree is a subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree. Examples: Input: Tree S 10 / \ 4 6 \ 30 Tr
11 min read
C Program for Red Black Tree Insertion
Following article is extension of article discussed here.In AVL tree insertion, we used rotation as a tool to do balancing after insertion caused imbalance. In Red-Black tree, we use two tools to do balancing. Recoloring Rotation We try recoloring first, if recoloring doesn't work, then we go for rotation. Following is detailed algorithm. The algor
6 min read
Optimal sequence for AVL tree insertion (without any rotations)
Given an array of integers, the task is to find the sequence in which these integers should be added to an AVL tree such that no rotations are required to balance the tree. Examples : Input : array = {1, 2, 3} Output : 2 1 3 Input : array = {2, 4, 1, 3, 5, 6, 7} Output : 4 2 6 1 3 5 7 Approach : Sort the given array of integers.Create the AVL tree
8 min read
Proto Van Emde Boas Tree | Set 3 | Insertion and isMember Query
Please see previous articles on Proto Van Emde Boas Tree to understand these properly. Procedure for Insert: Base Case: If the size of Proto-VEB is 2 then assign true to the bit array( Here we in code we assign Proto-VEB(1) due to recursive structure and so now it is not nullptr and it act as true ) at the position of key.Until we reach at the base
9 min read
Insertion in n-ary tree in given order and Level order traversal
Given a set of parent nodes where the index of the array is the child of each Node value, the task is to insert the nodes as a forest(multiple trees combined together) where each parent could have more than two children. After inserting the nodes, print each level in a sorted format. Example: Input: arr[] = {5, 3, -1, 2, 5, 3} Output:-1 231 5Input:
10 min read
Van Emde Boas Tree | Set 2 | Insertion, Find, Minimum and Maximum Queries
It is highly recommended to see previous articles on Van Emde Boas Tree first. Procedure for Insert : If no keys are present in the tree then simply assign minimum and maximum of the tree to the key.Otherwise we will go deeper in the tree and do the following:If the key we want to insert is less than the current minimum of the tree, then we swap bo
15+ min read
m-Way Search Tree | Set-2 | Insertion and Deletion
Insertion in an m-Way search tree: The insertion in an m-Way search tree is similar to binary trees but there should be no more than m-1 elements in a node. If the node is full then a child node will be created to insert the further elements. Let us see the example given below to insert an element in an m-Way search tree.Example: To insert a new el
15+ min read
POTD Solutions | 23 Nov’ 23 | AVL Tree Insertion
Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of AVL Trees but will also help you build up problem-solving skills. We recommend you to try this problem on our GeeksforGeeks Pract
12 min read
three90RightbarBannerImg