The Wayback Machine - https://web.archive.org/web/20241129133906/https://www.geeksforgeeks.org/insertion-in-binary-search-tree/
Open In App

Insertion in Binary Search Tree (BST)

Last Updated : 24 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a BST, the task is to insert a new node in this BST.

Example:

Insertion-in-BST

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 node. The below steps are followed while we try to insert a node into a binary search tree:

  • Initilize the current node (say, currNode or node) with root node
  • Compare the key with the current node.
  • Move left if the key is less than or equal to the current node value.
  • Move right if the key is greater than current node value.
  • Repeat steps 2 and 3 until you reach a leaf node.
  • Attach the new key as a left or right child based on the comparison with the leaf node’s value.

Follow the below illustration for a better understanding:

Insertion in Binary Search Tree using Recursion:

Below is the implementation of the insertion operation using recursion.

C++14
#include <iostream>
using namespace std;

struct Node {
    int key;
    Node* left;
    Node* right;    
    Node(int item) {
        key = item;
        left = NULL;
        right = NULL;
    }
};

// A utility function to insert a new node with 
// the given key
Node* insert(Node* node, int key) {
  
    // If the tree is empty, return a new node
    if (node == NULL) 
        return new Node(key);    
    
    // If the key is already present in the tree,
    // return the node
    if (node->key == key) 
        return node;
    
    // Otherwise, recur down the tree/ If the key
    // to be inserted is greater than the node's key,
    // insert it in the right subtree
    if (node->key < key) 
        node->right = insert(node->right, key);
    
    // If the key to be inserted is smaller than 
    // the node's key,insert it in the left subtree
    else 
        node->left = insert(node->left, key);
    
    // Return the (unchanged) node pointer
    return node;
}

// A utility function to do inorder tree traversal
void inorder(Node* root) {
    if (root != NULL) {
        inorder(root->left);
        cout << root->key << " ";
        inorder(root->right);
    }
}

// Driver program to test the above functions
int main() {
    // Creating the following BST
    //      50
    //     /  \
    //    30   70
    //   / \   / \
    //  20 40 60 80

    Node* root = new Node(50);
    root = insert(root, 30);
    root = insert(root, 20);
    root = insert(root, 40);
    root = insert(root, 70);
    root = insert(root, 60);
    root = insert(root, 80);

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

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

// Define the structure for a BST node
struct Node {
    int key;
    struct Node* left;
    struct Node* right;
};

// Function to create a new BST node
struct Node* newNode(int item) {
    struct Node* temp = 
       (struct Node*)malloc(sizeof(struct Node));
    temp->key = item;
    temp->left = temp->right = NULL;
    return temp;
}


// Function to insert a new node with the given key
struct Node* insert(struct Node* node, int key) {
  
    // If the tree is empty, return a new node
    if (node == NULL)
        return newNode(key);
    
    // If the key is already present in the tree,
    // return the node
    if (node->key == key)
        return node;
    
    // Otherwise, recur down the tree. If the key 
    // to be inserted is greater than the node's key,
    // insert it in the right subtree
    if (node->key < key)
        node->right = insert(node->right, key);
  
    // If the key to be inserted is smaller than 
    // the node's key,insert it in the left subtree
    else
        node->left = insert(node->left, key);

    // Return the (unchanged) node pointer
    return node;
}

// Function to perform inorder tree traversal
void inorder(struct Node* root) {
    if (root != NULL) {
        inorder(root->left);
        printf("%d ", root->key);
        inorder(root->right);
    }
}

// Driver program to test the above functions
int main() {
    // Creating the following BST
    //      50
    //     /  \
    //    30   70
    //   / \   / \
    //  20 40 60 80

    struct Node* root = newNode(50);
    root = insert(root, 30);
    root = insert(root, 20);
    root = insert(root, 40);
    root = insert(root, 70);
    root = insert(root, 60);
    root = insert(root, 80);

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

    return 0;
}
Java
class Node {
    int key;
    Node left, right;

    public Node(int item)
    {
        key = item;
        left = right = null;
    }
}

class GfG {

    // A utility function to insert a new node
    // with the given key
    static Node insert(Node root, int key)
    {

        // If the tree is empty, return a new node
        if (root == null)
            return new Node(key);

        // If the key is already present in the tree,
        // return the node
        if (root.key == key)
            return root;

        // Otherwise, recur down the tree
        if (key < root.key)
            root.left = insert(root.left, key);
        else
            root.right = insert(root.right, key);

        // Return the (unchanged) node pointer
        return root;
    }

    // A utility function to do inorder tree traversal
    static void inorder(Node root)
    {
        if (root != null) {
            inorder(root.left);
            System.out.print(root.key + " ");
            inorder(root.right);
        }
    }

    // Driver method
    public static void main(String[] args)
    {
        Node root = null;

        // Creating the following BST
        //      50
        //     /  \
        //    30   70
        //   / \   / \
        //  20 40 60 80

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

        // Print inorder traversal of the BST
        inorder(root);
    }
}
Python
# Python program to demonstrate
# insert operation in binary search tree
class Node:
    def __init__(self, key):
        self.left = None
        self.right = None
        self.val = key


# A utility function to insert
# a new node with the given key
def insert(root, key):
    if root is None:
        return Node(key)
    if root.val == key:
            return root
    if root.val < key:
            root.right = insert(root.right, key)
    else:
            root.left = insert(root.left, key)
    return root


# A utility function to do inorder tree traversal
def inorder(root):
    if root:
        inorder(root.left)
        print(root.val, end=" ")
        inorder(root.right)


# Creating the following BST
#      50
#     /  \
#    30   70
#   / \   / \
#  20 40 60 80
r = Node(50)
r = insert(r, 30)
r = insert(r, 20)
r = insert(r, 40)
r = insert(r, 70)
r = insert(r, 60)
r = insert(r, 80)

# Print inorder traversal of the BST
inorder(r)
C#
using System;

class Node {
    public int key;
    public Node left, right;

    public Node(int item) {
        key = item;
        left = right = null;
    }
}

class GfG {
  
    // A function to insert a new node with the given key
    public static Node Insert(Node node, int key) {
        if (node == null)
            return new Node(key);
      
        // Duplicates not allowed
        if (key == node.key)
            return node;
      
        if (key < node.key)
            node.left = Insert(node.left, key);
        else if (key > node.key)
            node.right = Insert(node.right, key);

        return node;
    }

    // A utility function to do inorder tree traversal
    public static void Inorder(Node root) {
        if (root != null) {
            Inorder(root.left);
            Console.Write(root.key + " ");
            Inorder(root.right);
        }
    }

    // Driver method
    public static void Main() {
        // Creating the following BST
        //      50
        //     /  \
        //    30   70
        //   / \   / \
        //  20 40 60 80

        Node root = new Node(50);
        root = Insert(root, 30);
        root = Insert(root, 20);
        root = Insert(root, 40);
        root = Insert(root, 70);
        root = Insert(root, 60);
        root = Insert(root, 80);

        // Print inorder traversal of the BST
        Inorder(root);
    }
}
JavaScript
class Node {
    constructor(key) {
        this.key = key;
        this.left = null;
        this.right = null;
    }
}

// A utility function to insert a new
// node with the given key
function insert(root, key) {

    if (root === null)
        return new Node(key);
        
    // Duplicates not allowed    
    if (root.key === key)
        return root;
        
    if (key < root.key)
        root.left = insert(root.left, key);
    else if (key > root.key)
        root.right = insert(root.right, key);

    return root;
}

// A utility function to do inorder
// tree traversal
function inorder(root) {
    if (root !== null) {
        inorder(root.left);
        console.log(root.key + " ");
        inorder(root.right);
    }
}

// Creating the following BST
//      50
//     /  \
//    30   70
//   / \   / \
//  20 40 60 80

let root = new Node(50);
root = insert(root, 30);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 70);
root = insert(root, 60);
root = insert(root, 80);

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

Output
20 30 40 50 60 70 80 

Time Complexity: 

  • The worst-case time complexity of insert operations is O(h) where h is the height of the Binary Search Tree. 
  • In the worst case, we may have to travel from the root to the deepest leaf node. The height of a skewed tree may become n and the time complexity of insertion operation may become O(n). 

Auxiliary Space: The auxiliary space complexity of insertion into a binary search tree is O(1)

Insertion in Binary Search Tree using Iterative approach:

Instead of using recursion, we can also implement the insertion operation iteratively using a while loop. Below is the implementation using a while loop.

C++
#include <iostream>
using namespace std;

struct Node {
    int key;
    Node* left;
    Node* right;
    Node(int item)
    {
        key = item;
        left = NULL;
        right = NULL;
    }
};

Node* insert(Node* root, int x)
{

    Node* temp = new Node(x);

    // If tree is empty
    if (root == NULL)
        return temp;

    // Find the node who is going
    // to have the new node temp as
    // it child. The parent node is
    // mainly going to be a leaf node
    Node *parent = NULL, *curr = root;
    while (curr != NULL) {
        parent = curr;
        if (curr->key > x)
            curr = curr->left;
        else if (curr->key < x)
            curr = curr->right;
        else
            return root;
    }

    // If x is smaller, make it
    // left child, else right child
    if (parent->key > x)
        parent->left = temp;
    else
        parent->right = temp;
    return root;
}

// A utility function to do inorder
// tree traversal
void inorder(Node* root)
{
    if (root != NULL) {
        inorder(root->left);
        cout << root->key << " ";
        inorder(root->right);
    }
}

// Driver program
int main()
{
    // Creating the following BST
    //      50
    //     /  \
    //    30   70
    //   / \   / \
    //  20 40 60 80

    Node* root = new Node(50);
    root = insert(root, 30);
    root = insert(root, 20);
    root = insert(root, 40);
    root = insert(root, 70);
    root = insert(root, 60);
    root = insert(root, 80);

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

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

// Define the structure for a BST node
struct Node {
    int key;
    struct Node* left;
    struct Node* right;
};

// Function to create a new BST node
struct Node* newNode(int item) {
    struct Node* temp = 
       (struct Node*)malloc(sizeof(struct Node));
    temp->key = item;
    temp->left = temp->right = NULL;
    return temp;
}


struct Node* insert(struct Node* root, int x)
{

    struct Node* temp = newNode(x);

    // If tree is empty
    if (root == NULL)
        return temp;

    // Find the node who is going
    // to have the new node temp as
    // it child. The parent node is
    // mainly going to be a leaf node
    struct Node *parent = NULL, *curr = root;
    while (curr != NULL) {
        parent = curr;
        if (curr->key > x)
            curr = curr->left;
        else if (curr->key < x)
            curr = curr->right;
        else
            return root;
    }

    // If x is smaller, make it
    // left child, else right child
    if (parent->key > x)
        parent->left = temp;
    else
        parent->right = temp;
    return root;
}

// Function to perform inorder tree traversal
void inorder(struct Node* root) {
    if (root != NULL) {
        inorder(root->left);
        printf("%d ", root->key);
        inorder(root->right);
    }
}

// Driver program to test the above functions
int main() {
    // Creating the following BST
    //      50
    //     /  \
    //    30   70
    //   / \   / \
    //  20 40 60 80

    struct Node* root = newNode(50);
    root = insert(root, 30);
    root = insert(root, 20);
    root = insert(root, 40);
    root = insert(root, 70);
    root = insert(root, 60);
    root = insert(root, 80);

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

    return 0;
}
Java
class Node {
    int key;
    Node left, right;
    public Node(int item)
    {
        key = item;
        left = right = null;
    }
}

class GfG {

    // Function to insert a new node with
    // the given key
    static Node insert(Node root, int x) {
        Node temp = new Node(x);

        // If tree is empty
        if (root == null) {
            return temp;
        }

        // Find the node who is going to have 
        // the new node temp as its child
        Node parent = null;
        Node curr = root;
        while (curr != null) {
            parent = curr;
            if (curr.key > x) {
                curr = curr.left;
            } else if (curr.key < x) {
                curr = curr.right;
            } else {
                return root; // Key already exists
            }
        }

        // If x is smaller, make it left 
        // child, else right child
        if (parent.key > x) {
            parent.left = temp;
        } else {
            parent.right = temp;
        }
        return root;
    }

    // A utility function to do inorder tree traversal
    static void inorder(Node root)
    {
        if (root != null) {
            inorder(root.left);
            System.out.print(root.key + " ");
            inorder(root.right);
        }
    }

    // Driver method
    public static void main(String[] args)
    {
        Node root = null;

        // Creating the following BST
        //      50
        //     /  \
        //    30   70
        //   / \   / \
        //  20 40 60 80

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

        // Print inorder traversal of the BST
        inorder(root);
    }
}
Python
# Python program to demonstrate
# insert operation in binary search tree
class Node:
    def __init__(self, key):
        self.left = None
        self.right = None
        self.key = key

def insert(root, key):
    temp = Node(key)

    # If tree is empty
    if root is None:
        return temp

    # Find the node who is going to 
    # have the new node temp as its child
    parent = None
    curr = root
    while curr is not None:
        parent = curr
        if curr.key > key:
            curr = curr.left
        elif curr.key < key:
            curr = curr.right
        else:
            return root  # Key already exists

    # If key is smaller, make it left 
    # child, else right child
    if parent.key > key:
        parent.left = temp
    else:
        parent.right = temp

    return root


# A utility function to do inorder tree traversal
def inorder(root):
    if root:
        inorder(root.left)
        print(root.key, end=" ")
        inorder(root.right)


# Creating the following BST
#      50
#     /  \
#    30   70
#   / \   / \
#  20 40 60 80
r = Node(50)
r = insert(r, 30)
r = insert(r, 20)
r = insert(r, 40)
r = insert(r, 70)
r = insert(r, 60)
r = insert(r, 80)

# Print inorder traversal of the BST
inorder(r)
C#
using System;

class Node {
    public int key;
    public Node left, right;

    public Node(int item) {
        key = item;
        left = right = null;
    }
}

class GfG {
  
    // Function to insert a new node with the given key
    public static Node Insert(Node root, int x)
    {
        Node temp = new Node(x);

        // If tree is empty
        if (root == null)
            return temp;

        // Find the node who is going to 
        // have the new node temp as its child
        Node parent = null;
        Node curr = root;
        while (curr != null)
        {
            parent = curr;
            if (curr.key > x)
                curr = curr.left;
            else if (curr.key < x)
                curr = curr.right;
            else
                return root; // Key already exists
        }

        // If x is smaller, make it left 
        // child, else right child
        if (parent.key > x)
            parent.left = temp;
        else
            parent.right = temp;

        return root;
    }
  
    // A utility function to do inorder tree traversal
    public static void Inorder(Node root) {
        if (root != null) {
            Inorder(root.left);
            Console.Write(root.key + " ");
            Inorder(root.right);
        }
    }

    // Driver method
    public static void Main() {
        // Creating the following BST
        //      50
        //     /  \
        //    30   70
        //   / \   / \
        //  20 40 60 80

        Node root = new Node(50);
        root = Insert(root, 30);
        root = Insert(root, 20);
        root = Insert(root, 40);
        root = Insert(root, 70);
        root = Insert(root, 60);
        root = Insert(root, 80);

        // Print inorder traversal of the BST
        Inorder(root);
    }
}
JavaScript
class Node {
    constructor(key)
    {
        this.key = key;
        this.left = null;
        this.right = null;
    }
}

// Function to insert a new node with the given key
function insert(root, x)
{
    const temp = new Node(x);

    // If tree is empty
    if (root === null)
        return temp;

    // Find the node who is going to have
    // the new node temp as its child
    let parent = null;
    let curr = root;
    while (curr !== null) {
        parent = curr;
        if (curr.key > x)
            curr = curr.left;
        else if (curr.key < x)
            curr = curr.right;
        else
            return root; // Key already exists
    }

    // If x is smaller, make it left
    // child, else right child
    if (parent.key > x)
        parent.left = temp;
    else
        parent.right = temp;

    return root;
}

// A utility function to do inorder tree traversal
function inorder(root)
{
    if (root !== null) {
        inorder(root.left);
        console.log(root.key + " ");
        inorder(root.right);
    }
}

// Creating the following BST
//      50
//     /  \
//    30   70
//   / \   / \
//  20 40 60 80

let root = new Node(50);
root = insert(root, 30);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 70);
root = insert(root, 60);
root = insert(root, 80);

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

Output
20 30 40 50 60 70 80 

The time complexity of inorder traversal is O(n), as each node is visited once. 
The Auxiliary space is O(n), as we use a stack to store nodes for recursion.

Related Links: 



Previous Article
Next Article

Similar Reads

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
Median of all nodes from a given range in a Binary Search Tree ( BST )
Given a Binary Search Tree (BST)consisting of N nodes and two nodes A and B, the task is to find the median of all the nodes in the given BST whose values lie over the range [A, B]. Examples: Input: A = 3, B = 11 Output: 6Explanation:The nodes that lie over the range [3, 11] are {3, 4, 6, 8, 11}. The median of the given nodes is 6. Input: A = 6, B
10 min read
Implement Binary Search Tree(BST) Iterator
Binary Search Trees (BSTs) are data structures, in computer science. They are commonly used for searching, insertion and deletion operations. In situations it becomes necessary to traverse a BST in an order. For example an in order traversal visits nodes in ascending order based on their values. This article explores the creation of a BSTIterator c
6 min read
Count permutations of given array that generates the same Binary Search Tree (BST)
Given an array, arr[] of size N consisting of elements from the range [1, N], that represents the order, in which the elements are inserted into a Binary Search Tree, the task is to count the number of ways to rearrange the given array to get the same BST. Examples: Input: arr[ ] ={3, 4, 5, 1, 2}Output: 6Explanation :The permutations of the array w
10 min read
Deletion in Binary Search Tree (BST)
Given a BST, the task is to delete a node in this BST, which can be broken down into 3 scenarios: Case 1. Delete a Leaf Node in BST Case 2. Delete a Node with Single Child in BST Deleting a single child node is also simple in BST. Copy the child to the node and delete the node.  Case 3. Delete a Node with Both Children in BST Deleting a node with b
10 min read
Binary Search Tree (BST) Traversals – Inorder, Preorder, Post Order
Given a Binary Search Tree, The task is to print the elements in inorder, preorder, and postorder traversal of the Binary Search Tree.  Input:  Output: Inorder Traversal: 10 20 30 100 150 200 300Preorder Traversal: 100 20 10 30 200 150 300Postorder Traversal: 10 30 20 150 300 200 100 Input:  Output: Inorder Traversal: 8 12 20 22 25 30 40Preorder Tr
11 min read
LCA in BST - Lowest Common Ancestor in Binary Search Tree
Given two values n1 and n2 in a Binary Search Tree, find the Lowest Common Ancestor (LCA). You may assume that both values exist in the tree. The lowest common ancestor between two nodes n1 and n2 is defined as the lowest node that has both n1 and n2 as descendants (where we allow a node to be a descendant of itself). In other words, the LCA of n1
15+ min read
Searching in Binary Search Tree (BST)
Given a BST, the task is to search a node in this BST. For searching a value in BST, consider it as a sorted array. Now we can easily perform search operation in BST using Binary Search Algorithm. Input: Root of the below BST Output: TrueExplanation: 8 is present in the BST as right child of rootInput: Root of the below BST Output: FalseExplanation
7 min read
Binary Search Tree vs Ternary Search Tree
For effective searching, insertion, and deletion of items, two types of search trees are used: the binary search tree (BST) and the ternary search tree (TST). Although the two trees share a similar structure, they differ in some significant ways. FeatureBinary Search Tree (BST)Ternary Search Tree (TST)NodeHere, each node has at most two children. H
3 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, wi
2 min read
Binary Tree to Binary Search Tree Conversion
Given a Binary Tree, the task is to 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. Examples Input: Output: Explanation: The above Binary tree is converted to Binary Search tree by keeping the original structure of Binary Tree. Approach: The idea to recursively trav
7 min read
Binary Tree to Binary Search Tree Conversion using STL set
Given a Binary Tree, the task is to 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. Example: Input: Output: Explanation: The above Binary tree is converted to Binary Search tree by keeping the original structure of Binary Tree. Approach: The idea is to recursively t
7 min read
Minimum swap required to convert binary tree to binary search tree
Given an array arr[] which represents a 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 swaps required to convert it into a Binary Search Tree. Examples: Input: arr[] = [5, 6, 7, 8, 9, 10, 11]Output: 3Explanation:Binary tree of the g
9 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
Search and Insertion in K Dimensional tree
What is K dimension tree? A K-D Tree(also called as K-Dimensional Tree) is a binary search tree where data in each node is a K-Dimensional point in space. In short, it is a space partitioning(details below) data structure for organizing points in a K-Dimensional space. A non-leaf node in K-D tree divides the space into two parts, called as half-spa
15+ min read
POTD Solutions | 15 Oct' 23 | Normal BST to Balanced BST
View all POTD Solutions 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 Binary Search Trees but will also help you build up problem-solving skills. POTD 15 October: Normal BST t
5 min read
K'th Largest Element in BST when modification to BST is not allowed
Given a Binary Search Tree (BST) and a positive integer k, the task is to find the kth largest element in the Binary Search Tree. Example: Input: k = 3 Output: 14Explanation: If we sort the BST in decreasing order, then it will become 22, 20, 14, 12, 10, 8, 4. 14 is the 3rd largest element. Table of Content Using Recursion - O(n) Time and O(h) Spac
11 min read
k-th Smallest in BST (Order Statistics in BST)
Given a Binary Search Tree (BST) and a positive integer k, find the kth smallest element in the Binary Search Tree. Example: Input: k = 3 Output: 10Explanation: If we sort the BST in increasing order, then it will become 4, 8, 10, 12, 14, 20, 22. 10 is the 3rd smallest element. Table of Content [Expected Approach - 1] Using In-Order traversal - O(n
13 min read
Search N elements in an unbalanced Binary Search Tree in O(N * logM) time
Given an Unbalanced binary search tree (BST) of M nodes. The task is to find the N elements in the Unbalanced Binary Search Tree in O(N*logM) time. Examples: Input: search[] = {6, 2, 7, 5, 4, 1, 3}. Consider the below tree Output:FoundNot FoundFoundFoundFoundFoundNot Found Naive Approach: For each element, we will try to search for that element in
8 min read
Meta Binary Search | One-Sided Binary Search
Meta binary search (also called one-sided binary search by Steven Skiena in The Algorithm Design Manual on page 134) is a modified form of binary search that incrementally constructs the index of the target value in the array. Like normal binary search, meta binary search takes O(log n) time. Meta Binary Search, also known as One-Sided Binary Searc
9 min read
Threaded Binary Tree | Insertion
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 Ino
13 min read
Insertion in a Binary Tree in level order
Given a binary tree and a key, the task is to insert the key into the binary tree at the first position available in level order manner. Examples: Input: key = 12 Output: Explanation: Node with value 20 is inserted into the binary tree at the first position available in level order manner. Approach: The idea is to do an iterative level order traver
8 min read
Convert a BST to a Binary Tree such that sum of all greater keys is added to every key
Given a Binary Search Tree (BST), convert it to a Binary Tree such that every key of the original BST is changed to key plus sum of all greater keys in BST. Examples: Input: Root of following BST 5 / \ 2 13 Output: The given BST is converted to following Binary Tree 18 / \ 20 13 Method 1: Solution: Do reverse In order traversal. Keep track of the s
15+ min read
Check if a Binary Tree (not BST) has duplicate values
Check if a Binary Tree (not BST) has duplicate values To check if a binary tree has duplicate values, you can follow these steps: Create a set to store the values that have been encountered so far.Start a traversal of the binary tree. For each node, check if its value is in the set. If it is, return true to indicate that the tree contains duplicate
10 min read
Build Binary Tree from BST such that it's level order traversal prints sorted data
Construct a Binary Tree from the given Binary Search Tree such that it's level order traversal outputs sorted data.Examples: Input: Output: 1 2 3 Input: Output: 1 2 3 4 5 Approach: Perform the inorder traversal of the given Binary Search Tree.Add each node in level order to the Binary Tree.Finally, print the level order traversal of the created Bin
12 min read
Check if a Binary Tree is BST : Simple and Efficient Approach
Given a Binary Tree, the task is to check whether the given binary tree is Binary Search Tree or not.A binary search tree (BST) is a node-based binary tree data structure which has the following properties. The left subtree of a node contains only nodes with keys less than the node's key.The right subtree of a node contains only nodes with keys gre
6 min read
Check if the Binary Tree contains a balanced BST of size K
Given a Binary Tree and a positive integer K. The task is to check whether the Balanced BST of size K exists in a given Binary Tree or not. If it exists then print “Yes” else print “No”. Examples: Input: K = 4, Below is the given Tree: 15 / \ 10 26 / \ / \ 5 12 25 40 / / \ 20 35 50 \ 60 Output: Yes Explanation: Subtree of the given tree with size k
13 min read
Convert a Binary Tree to BST by left shifting digits of node values
Given a Binary Tree of positive integers. The task is to convert it to a BST using left shift operations on the digits of the nodes. If it is not possible to convert the binary tree to BST then print -1. Examples: Input: 443 / \ 132 543 / \ 343 237 Output: 344 / \ 132 435 / \ 433 723 Explanation: 443 ? left shift two times ? 344 132 ? zero shift op
12 min read
Iterative approach to check if a Binary Tree is BST or not
Given a Binary Tree, the task is to check if the given binary tree is a Binary Search Tree or not. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: 9 / \ 6 10 / \ \ 4 7 11 / \ \ 3 5 8 Output: YES Explanation: Since the left subtree of each node of the tree consists of smaller valued nodes and the right subtree of each
9 min read
Check if a Binary Tree is BST or not
Given the root of a binary tree. Check whether it is a Binary Search Tree or not. A Binary Search Tree (BST) is a node-based binary tree data structure with the following properties. All keys in the left subtree are smaller than the root and all keys in the right subtree are greater.Both the left and right subtrees must also be binary search trees.
15+ min read
Article Tags :
three90RightbarBannerImg