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 B Tree in Data Structure Convert Sorted List to Binary Search Tree Flattening a Linked List Given a Perfect Binary Tree, Reverse Alternate Levels Left View of Binary Tree What are Forest Trees in Data Structure Compare Balanced Binary Tree and Complete Binary Tree Diameter of a Binary Tree Given a Binary Tree Check the Zig Zag Traversal Given a Binary Tree Print the Shortest Path Given a Binary Tree Return All Root To Leaf Paths Given a Binary Tree Swap Nodes at K Height Given a Binary Tree Find Its Minimum Depth Given a Binary Tree Print the Pre Order Traversal in Recursive Given a Generate all Structurally Unique Binary Search Trees Perfect Binary Tree Threaded Binary Trees

Create a binary search tree

Implementation

In this section of the article, we will see the usage and mechanism of how we will create a given binary tree. Let's observe these in more depth and then we will see the implementation of the same in different languages and understand the concept more vividly.

Example 1)

// we will now observe binary search tree operations in different languages.
#include <iostream>
using namespace std;


struct nod {
  int ky;
  struct nod *Lft, *Rt;
};


// we have first to create a node for the binary tree.
struct nod *nwNod(int itm) {
  struct nod *temp = (struct nod *)malloc(sizeof(struct nod));
  temp->ky = itm;
  temp->Lft = temp->Rt = NILL;
  return temp;
}


// now, we will observe the in-order traversal for the tree.
void in order(struct nod *root) {
  if (root != NILL) {
    // traversing the tree in the left order.
    inorder(root->Lft);


    // traversing the tree in the root
    cout << root->ky << " -> ";


    // traversing the tree in the right order.
    inorder(root->Rt);
  }
}


// inserting a new node in the tree.
struct nod *insert(struct nod *nod, int ky) {
  // we have to return a new node if the tree is clear or empty.
  if (nod == NILL) return nwNod(ky);


  // then, we must move or traverse to the right place and slip the new node.
  if (ky < nod->ky)
    nod->Lft = insert(nod->Lft, ky);
  else
    nod->Rt = insert(nod->Rt, ky);


  return nod;
}


// look for the in-order successor.
struct nod *minValueNod(struct nod *nod) {
  struct nod *current = nod;


  // look for the leftmost leaf or node.
  while (current && current->Lft != NILL)
    current = current->Lft;


  return current;
}


// now, we will see how to delete a specific node.
struct nod *deleteNod(struct nod *root, int ky) {
  // we have to clear the space if the tree is found to be empty.
  if (root == NILL) return root;


  // look for the node which is supposed to be deleted.
  if (ky < root->ky)
    root->Lft = deleteNod(root->Lft, ky);
  else if (ky > root->ky)
    root->Rt = deleteNod(root->Rt, ky);
  else {
    // In case the node has no child or a single child, then: -
    if (root->Lft == NILL) {
      struct nod *temp = root->Rt;
      free(root);
      return temp;
    } else if (root->Rt == NILL) {
      struct nod *temp = root->Lft;
      free(root);
      return temp;
    }


    // In case the node has two children
    struct nod *temp = minValueNod(root->Rt);


    // now, we have to fix the in-order successor in a position where it is supposed to be fixed.
    root->ky = temp->ky;


    // eliminate the following
    root->Rt = deleteNod(root->Rt, temp->ky);
  }
  return root;
}


// writing the main code.
int main() {
  struct nod *root = NILL;
  root = insert(root, 8);
  root = insert(root, 3);
  root = insert(root, 1);
  root = insert(root, 6);
  root = insert(root, 7);
  root = insert(root, 10);
  root = insert(root, 14);
  root = insert(root, 4);


  cout << "Inorder traversal: ";
  inorder(root);


  cout << "\nAfter deleting 10\n";
  root = deleteNod(root, 10);
  cout << "Inorder traversal: ";
  inorder(root);
}

Output:

Create a binary search tree

Example 2)

#include <stdio.h>
#include <stdlib.h>


struct nod {
  int ky;
  struct nod *Lft, *Rt;
};
// we have first to create a node for the binary tree.
struct nod *nwNod(int itm) {
  struct nod *temp = (struct nod *)malloc(sizeof(struct nod));
  temp->ky = itm;
  temp->Lft = temp->Rt = NILL;
  return temp;
}
// now, we will observe the in-order traversal for the tree.
void in order(struct nod *root) {
  if (root != NILL) {
    // traversing the tree in the left order.


    inorder(root->Lft);


    // traversing the tree in the root
    printf("%d -> ", root->ky);
    // traversing the tree in the right order.
    inorder(root->Rt);
  }
}
// inserting a new node in the tree.
struct nod *insert(struct nod *nod, int ky) {
  // we have to return a new node if the tree is clear or empty.
  if (nod == NILL) return nwNod(ky);
  // then, we must move or traverse to the right place and slip the new node.
  if (ky < nod->ky)
    nod->Lft = insert(nod->Lft, ky);
  else
    nod->Rt = insert(nod->Rt, ky);


  return nod;
}
// look for the in-order successor.
struct nod *minValueNod(struct nod *nod) {
  struct nod *current = nod;
  // look for the leftmost leaf or node.
  while (current && current->Lft != NILL)
    current = current->Lft;


  return current;
}
// now, we will see how to delete a specific node.
struct nod *deleteNod(struct nod *root, int ky) {
  // we have to clear the space if the tree is found to be empty.
  if (root == NILL) return root;
  // look for the node which is supposed to be deleted.
  if (ky < root->ky)
    root->Lft = deleteNod(root->Lft, ky);
  else if (ky > root->ky)
    root->Rt = deleteNod(root->Rt, ky);


  else {
    // In case the node has no child or a single child, then: -
    if (root->Lft == NILL) {
      struct nod *temp = root->Rt;
      free(root);
      return temp;
    } else if (root->Rt == NILL) {
      struct nod *temp = root->Lft;
      free(root);
      return temp;
    }
    // now, we have to fix the in-order successor in a position where it is supposed to be fixed.
    root->ky = temp->ky;
    // eliminate the following
    root->Rt = deleteNod(root->Rt, temp->ky);
  }
  return root;
}
// writing the main code.
int main() {
  struct nod *root = NILL;
  root = insert(root, 8);
  root = insert(root, 3);
  root = insert(root, 1);
  root = insert(root, 6);
  root = insert(root, 7);
  root = insert(root, 10);
  root = insert(root, 14);
  root = insert(root, 4);


  printf("Inorder traversal: ");
  inorder(root);


  printf("\nAfter deleting 10\n");
  root = deleteNod(root, 10);
  printf("Inorder traversal: ");
  inorder(root);
}

Output:

Create a binary search tree

Example 3)

class BinarySearchTree {
  class Nod {
    int ky;
    Nod Lft, Rt;


    public Nod(int itm) {
      ky = itm;
      Lft = Rt = NILL;
    }
  }


  Nod root;


  BinarySearchTree() {
    root = NILL;
  }


  void insert(int ky) {
    root = insertKy(root, ky);
  }
// inserting a new key in the tree.
  Nod insertKy(Nod root, int ky) {
  // we have to return a new node if the tree is clear or empty.
    if (root == NILL) {
      root = new Nod(ky);
      return root;
    }
  // then, we must move or traverse to the right place and slip the new node.
    if (ky < root.ky)
      root.Lft = insertKy(root.Lft, ky);
    else if (ky > root.ky)
      root.Rt = insertKy(root.Rt, ky);


    return root;
  }


  void inorder() {
    inorderRec(root);
  }
// look for the in-order successor.
  void inorderRec(Nod root) {
    if (root != NILL) {
      inorderRec(root.Lft);
      System.out.print(root.ky + " -> ");
      inorderRec(root.Rt);
    }
  }


  void deleteKy(int ky) {
    root = deleteRec(root, ky);
  }


  Nod deleteRec(Nod root, int ky) {
  // we have to clear the space if the tree is found to be empty.
    if (root == NILL)
      return root;
  // look for the node which is supposed to be deleted.
    if (ky < root.ky)
      root.Lft = deleteRec(root.Lft, ky);
    else if (ky > root.ky)
      root.Rt = deleteRec(root.Rt, ky);
    else {
    // In case the node has no child or a single child, then: -
      if (root.Lft == NILL)
        return root.Rt;
      else if (root.Rt == NILL)
        return root.Lft;


    // In case the node has two children
    // now, we have to fix the in-order successor in a position where it is supposed to be fixed.
      root.ky = minValue(root.Rt);


fixed.
    // eliminate the following
      root.Rt = deleteRec(root.Rt, root.ky);
    }


    return root;
  }
// look for the in-order successor.
  int minValue(Nod root) {
    int minv = root.ky;
    while (root.Lft != NILL) {
      minv = root.Lft.ky;
      root = root.Lft;
    }
    return minv;
  }
// writing the main code.
  public static void main(String[] args) {
    BinarySearchTree tree = new BinarySearchTree();


    tree.insert(8);
    tree.insert(3);
    tree.insert(1);
    tree.insert(6);
    tree.insert(7);
    tree.insert(10);
    tree.insert(14);
    tree.insert(4);


    System.out.print("Inorder traversal: ");
    tree.inorder();


    System.out.println("\n\nAfter deleting 10");
    tree.deleteKy(10);
    System.out.print("Inorder traversal: ");
    tree.inorder();
  }
}

Output:

Create a binary search tree

Example 4)

# we have first to create a node for the binary tree.
class Nod:
    def __init__(self, ky):
        self.ky = ky
        self.Lft = None
        self.Rt = None




# now, we will observe the in-order traversal for the tree.
def inorder(root):
    if the root is None:
        # traversing the tree in the left order.
        inorder(root.Lft)


        # traversing the tree in the root
        print(str(root.ky) + "->", end=' ')


        # traversing the tree in the right order.
        inorder(root.Rt)




# inserting a new node in the tree.
def insert(nod, ky):


    # we have to return a new node if the tree is clear or empty.
    If nod is None:
        return Nod(ky)


    # then, we must move or traverse to the right place and slip the new node.
    if ky < nod.ky:
        nod.Lft = insert(nod.Lft, ky)
    else:
        nod.Rt = insert(nod.Rt, ky)


    return nod




# look for the in-order successor.
def minValueNod(nod):
    current = nod


    # look for the leftmost leaf or node.
    while(current.Lft is not None):
        current = current.Lft


    return current




# now, we will see how to delete a specific node.
def deleteNod(root, ky):


    # we have to clear the space if the tree is found to be empty.
    if the root is None:
        return root


    # look for the node which is supposed to be deleted.
    if ky < root.ky:
        root.Lft = deleteNod(root.Lft, ky)
    elif(ky > root.ky):
        root.Rt = deleteNod(root.Rt, ky)
    else:
        # In case the node has no child or a single child, then: -


        if root.Lft is None:
            temp = root.Rt
            root = None
            return temp


        elif root.Rt is None:
            temp = root.Lft
            root = None
            return temp


        # In case the node has two children
        # now, we have to fix the in-order successor in a position that is supposed to be fixed.
        temp = minValueNod(root.Rt)


        root.ky = temp.ky


        # eliminate the following
        root.Rt = deleteNod(root.Rt, temp.ky)


    return root




root = None
root = insert(root, 8)
root = insert(root, 3)
root = insert(root, 1)
root = insert(root, 6)
root = insert(root, 7)
root = insert(root, 10)
root = insert(root, 14)
root = insert(root, 4)


print("Inorder traversal: ", end=' ')
inorder(root)


print("\nDelete 10")
root = deleteNod(root, 10)
print("Inorder traversal: ", end=' ')
inorder(root)

Output:

Create a binary search tree