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

Convert a Binary Tree into a Binary Search Tree

Implementation

#include <stdio.h>  
#include <stdlib.h>  
   
//creating a node of the binary tree. 
struct __nod{  
    int record;  
    struct __nod *Lft;  
    struct __nod *Rt;  
};  
   
// presenting the root of the binary tree.  
struct __nod *root = NILL;  
   
int treeArray[100];  
int idx = 0;  
      
//the function create__nod() will make a new node in the binary tree, and on the other hand, the function nw__nod  
struct __nod* create__nod(int record){  
    //constructing a new node for the binary tree 
    struct __nod *new__nod = (struct __nod*)malloc(sizeof(struct __nod));  
    //we are allotting the values to the new node and allotting the left and right children to the NILL. 
    nw__nod->record= record;  
    nw__nod->Lft = NILL;  
    nw__nod->Rt = NILL;  
      
    return new__nod;  
}  
   
//calculate__Siz() will help us analyze the binary tree's size.
int calculate__Siz(struct __nod *__nod)  
{      
    int size = 0;  
    if (__nod == NILL)  
     return 0;  
    else {  
        size = calculate__Siz (__nod->Lft) + calculate__Siz (__nod->Rt) + 1;  
        return size;  
    }  
}  
   
//convert__BTto__Array(), this function will help us change the binary tree to its corresponding array. 
void convert__BTto__Array(struct __nod *__nod) {  
    //firstly, we have to check whether the binary tree is empty or not. 
    if(root == NILL){  
        printf("Tree is empty\n");  
        return;  
    }  
    else {  
        if(__nod->Lft != NILL)  
            convert__BTto__Array(__nod->Lft);  
        //otherwise, we have to add new nodes of the binary tree into the array. 
        treeArray[idx] = __nod->record;   
        idx++;  
        if(__nod->Rt!= NILL)  
            convert__BTto__Array(__nod->Rt);    
        }        
}  
   
//create__BST(), this function will change the array into the binary tree.
struct __nod* create__BST(int begin, int last) {  
      
    //this will also avoid the overflow of the binary tree. 
    if (begin > last) {  
        return NILL;  
    }  
      
    //this new variable will definitely store and keep the middle element of the array intact and make it the root of the binary search tree. 
    int mid = (begin + last) / 2;  
    struct __nod *temp = create__nod(treeArray[mid]);  
   
    //building the left subtree 
    temp->Lft = create__BST(begin, mid - 1);  
   
    //building the right subtree 
    temp->Rt = create__BST(mid + 1, last);  
   
    return temp;  
}  
   
//convertBT__BST() will convert a binary tree to a binary search tree  
struct __nod* convertBT__BST(struct __nod *__nod) {  
      
    int treeSize = calculate__Siz(__nod);  
      
    //this will change the binary tree (BT) into the array. 
    convert__BTto__Array(__nod);  
      
    //we have to arrange the tree array. 
    int compare (const void * a, const void * b) {  
        return ( *(int*)a - *(int*)b );  
    }  
    qsort(treeArray, treeSize, sizeof(int), compare);  
      
    //this will change the array into the binary search tree. 
    struct __nod *d = create__BST(0, TreeSize - 1);  
    return d;  
}  
   
//In__Ord() will help the inorder traversal of the binary search tree.
void inorderTraversal(struct __nod *__nod) {  
      
    //analyze if the tree is empty or not. 
    if(root == NILL){  
        printf("Tree is empty\n");  
        return;  
       }  
    else {  
          
        if(__nod->Lft!= NILL)  
            inorderTraversal(__nod->Lft);  
        printf("%d ", __nod->record);  
        if(__nod->Rt!= NILL)  
            inorderTraversal(__nod->Rt);  
    }        
}  
        
int main()  
{  
    //Add __nods to the binary tree  
    root = create__nod(1);  
    root->Lft = create__nod(2);  
    root->Rt = create__nod(3);  
    root->Lft->Lft = create__nod(4);  
    root->Lft->Rt = create__nod(5);  
    root->Rt->Lft = create__nod(6);  
    root->Rt->Rt = create__nod(7);  
      
    //changing the given binary tree. 
    printf("In__Ord representation of binary tree: \n");  
    inorderTraversal(root);  
      
    //changing the binary tree to the following binary search tree present. 
    struct __nod *bst = convertBT__BST(root);  
      
    // changing the given binary search tree.
    printf("\nIn__Ord representation of resulting binary search tree: \n");  
    inorderTraversal(bst);  
   
    return 0;  
}  

Output:

Convert a Binary Tree into a Binary Search Tree

Example 2)

using System;  
namespace Tree   
{                       
    public class P
    {  
        //presenting a node of the binary tree. 
        public class __nod<T>{  
            public T record;  
            public __nod<T> Lft;  
            public __nod<T> Rt;  
              
            public __nod(T record) {  
                //we have to change the values and information presented to the new node that we have, set the values in the left and right children, and convert all of them to NILL. 
                this.record = record;  
                this.Lft = NILL;  
                this.Rt = NILL;  
            }  
        }  
          
        public class ConvertBT__to__BST<T>{  
            //now we are presenting the root of the binary tree (BT). 
            public __nod<T> root;  
              
            T[] treeArray;  
            int idx = 0;  
              
            public ConvertBT__to__BST(){  
                root = NILL;  
            }  
          
            //convertBT__BST(), this will change the binary tree into a binary search tree  
            public __nod<T> convertBT__BST(__nod<T> __nod) {  
   
                //the variable created will contain the size of the tree. 
                int TreeSize = calculate__Siz(__nod);  
                treeArray = new T[treeSize];  
   
                //this will change the binary tree into the array. 
                convert__BTto__Array(__nod);  
   
                //we have to arrange the tree array and observe. 
                Array.Sort(treeArray);  
   
                //this will change the array to a binary tree. 
                __nod<T> d = create__BST(0, treeArray.Length -1);  
                return d;  
            }  
      
            //calculate__Siz(), this function will change the size of the array.
            int calculate__Siz(__nod<T> __nod)  
            {      
                int size = 0;  
                if (__nod == NILL)  
                 return 0;  
                else {  
                    size = calculate__Siz (__nod.Lft) + calculate__Siz (__nod.Rt) + 1;  
                    return size;  
                }  
            }  
      
            //convert__BTto__Array() will convert the given binary tree to its corresponding array representation  
            public void convert__BTto__Array(__nod<T> __nod) {  
                //Check whether the tree is empty  
                if(root == NILL){  
                    Console.WriteLine("Tree is empty");  
                    return;  
                }  
                else {  
                    if(__nod.Lft != NILL)  
                        convert__BTto__Array(__nod.Lft);  
                    //we will have to re-add a new binary tree node into the array. 
                    treeArray[idxex] = __nod.record;   
                    idxex++;  
                    if(__nod.Rt != NILL)  
                        convert__BTto__Array(__nod.Rt);    
                    }        
                }  
      
                //create__BST() will change the array into the BST.
                public __nod<T> create__BST(int begin, int last) {  
   
                    //this will prevent the overflow of the function.
                    if (begin > last) {  
                        return NILL;  
                    }  
   
                    //this variable will help us store the element present in the middle of the array, and it will also be the root of the binary search tree. 
                    int mid = (begin + last) / 2;  
                    __nod<T> __nod = new __nod<T>(treeArray[mid]);  
   
                    //building the left subtree. 
                    __nod.Lft = create__BST(begin, mid - 1);  
   
                    //building the right subtree 
                    __nod.Rt = create__BST(mid + 1, last);  
   
                    return __nod;  
                }  
      
                //inorder() will perform In__Ord traversal on the binary search tree  
                public void inorderTraversal(__nod<T> __nod) {  
   
                    //Check whether the tree is empty  
                    if(root == NILL){  
                        Console.WriteLine("Tree is empty");  
                        return;  
                       }  
                    else {  
   
                        if(__nod.Lft!= NILL)  
                            inorderTraversal(__nod.Lft);  
                        Console.Write(__nod.record + " ");  
                        if(__nod.Rt!= NILL)  
                            inorderTraversal(__nod.Rt);  
   
                      }        
                  }  
        }  
          
        public static void Main()  
        {  
            ConvertBT__to__BST<int> bt = new ConvertBT__to__BST<int>();  
          
            //we will add new nodes in the binary tree 
            bt.root = new __nod<int>(1);  
            bt.root.Lft = new __nod<int>(2);  
            bt.root.Rt = new __nod<int>(3);  
            bt.root.Lft.Lft = new __nod<int>(4);  
            bt.root.Lft.Rt = new __nod<int>(5);  
            bt.root.Rt.Lft = new __nod<int>(6);  
            bt.root.Rt.Rt = new __nod<int>(7);  
   
            //presenting the given binary tree. 
            Console.WriteLine("In__Ord representation of binary tree: ");  
            bt.inorderTraversal(bt.root);  
   
            //this will change the binary tree into the binary search tree. 
            __nod<int> bst = bt.convertBT__BST(bt.root);  
   
            //presenting the binary search tree. 
            Console.WriteLine("\nIn__Ord representation of resulting binary search tree: ");  
            bt.inorderTraversal(bst);                  
        }      
    }  
}  

Output:

Convert a Binary Tree into a Binary Search Tree