×

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

Related Topics

Horizontal and Vertical Scaling

Being a software engineer, you would have designed a website or application and deployed it on any server. Imagine that the developed application starts getting popular, and many users engage...

6 minutes read.

Inorder Successor in Binary Trees

The next node in the Inorder traversal of a binary tree is known as Inorder successor of that particular node. In a Binary Search Tree, the definition of Inorder successor can...

9 minutes read.

Hashing

Hashing: Hashing is a process in which a large amount of data is mapped to a small table with the help of hashing function. It is a searching technique. Hash table We...

4 minutes read.

Object-Oriented Analysis and Design

While designing a system, one should know all the requirements or needs of the plan beforehand, and to do so, we should use a systematic approach to analyze the goal...

3 minutes read.

Check if a Singly Linked List is Palindrome

Check if a Singly Linked List is Palindrome In this section, we have given a singly linked list, and we need to check whether the given list is a palindrome. Example:           1...

3 minutes read.

Delete the Middle element of the Linked List in C

Delete the Middle element of the Linked List in C This article has given a singly linked list and will delete the middle element of the given linked list. Example:  The given...

3 minutes read.

Equal Sum

Find an element in array such that the sum of left array is equal to the sum of right array You have been given an array of numbers. You have to...

4 minutes read.

Introduction and Implementation of Bloom Filter

It often happens with many of us that when we create an account on some applications like Github, it shows us that the username already exists. You can add some...

4 minutes read.

Operations on Queue in Data Structures

A queue is a linear structure where operations are done in a specific sequence. Queues are abstract data structures that are comparable to Stacks. A queue, unlike a stack, is...

8 minutes read.

What is the Use of Segment Trees in Data Structure?

Segment trees Segment trees are also called statistical trees in computer science. They are a type of tree data structure. Segment trees are used to store information regarding segments and intervals....

6 minutes read.

Binary Search Tree vs AVL Tree: Data Structure

Difference Between Binary Search Tree and AVL Tree Binary Search Tree: The binary search tree is a kind of binary tree data structure and it follows the conditions of binary...

3 minutes read.

Bookshop management system using file handling in C++

We see different software in every hospitals or library to manage their database. It is very important to store organization’s data. So we use this software. Now we are going...

5 minutes read.

What is a Spanning Tree in Data Structure

Data structures Data management is called database management. This allows the computer to sort or organize the data for efficient retrieval. A data model is a system used to store, manage,...

5 minutes read.

Deletion in B+ Tree

Make a search for the leaf node that containing the key value by taking the value in a key value. If the required key value is found, then it will remove...

6 minutes read.

What is the difference between Tree and Graph

We usually use a diverse range of data structure to store our data and information. To store them in a more sequential manner and to access them easily, we use...

4 minutes read.

Flattening a Linked List

In this article, we are going to study about the logic behind the flattening of linked list and we also going to build a code in the C++ to flatten...

3 minutes read.

Circular Queue

Circular Queue Circular Queue is special type queue, which follows First in First Out (FIFO) rule and as well as instead of ending queue at the last position, it starts again...

4 minutes read.

Traversal of binary tree

Traversal of binary tree: A node is visited only once in the traversal of the binary tree. There are three main types of traversal methods in the binary tree. In-order traversalPre-order...

3 minutes read.

Difference between complete and full binary tree

As we all know that the  binary tree is a tree it contains one or two children at each other node. It contains two children's nodes in the Binary tree. The...

6 minutes read.

Array vs Linked List: Data Structure

Data structure: Difference Between Array and Linked List What is Array? An array is a linear data structure that can store similar data items for further processing. The similar data items...

3 minutes read.