Skip to main content

C++ program to convert Sorted Array to binary search tree

Binary Search Tree is a node-based binary tree data structure which has the following properties:
  • The left subtree of a node contains only nodes with keys lesser than the node%u2019s key.
  • The right subtree of a node contains only nodes with keys greater than the node%u2019s key.
  • The left and right subtree each must also be a binary search tree.
Algorithm
The mid-value of the given sorted array would represent the root of one possible BST that can be constructed from the given array elements.
1. Find the middle element of the array and make it root(Now the array is divided into two halves left and right, where the left half is our left subtree and right half, is our right subtree)
2. Recursively do the same for the left half and right half.
       (a) Get the middle of left half and make it left child of the root created into Step 1.
       (b) Get the middle of right half and make it right child of the root created into Step 1.
3. The base condition that would terminate the recursion would then be if low boundary index            exceeds high boundary index, in which case return null.

#include<iostream> using namespace std; struct Node { int data; Node *left; //pointer points to left node Node *right; //pointer points to right node }; /*function that returns new node*/ Node *newNode(int x) { Node *temp = new Node(); //temp points to the dyanamically formed node temp->data = x; temp->left = NULL; temp->right = NULL; return temp; //return the address of the node temp is pointing } Node *arrayToBST(int *arr, int start, int end) { /* Base Case*/ if(start > end) { return NULL; } /*Get the middle element and make it root*/ int mid = (start + end)/2; Node *root = newNode(arr[mid]); /* Recursively construct the left subtree and make it left child of root */ root->left = arrayToBST(arr,start,mid-1); /* Recursively construct the right subtree and make it right child of root */ root->right = arrayToBST(arr,mid+1,end); return root; } /*Function inOrder prints inorder traversal of the tree inorder traversal prints element in sorted order
*/ void inOrder(Node *node) { if(node == NULL) return; inOrder(node->left); cout<<node->data<<" "; inOrder(node->right); } int main() { int arr[] = {2, 4, 5, 6, 7, 10, 11, 15}; /*Number of elements in the array (total size of the array / size of one element ) In this case elements are integer */ int n = sizeof(arr)/sizeof(arr[0]); Node *root = arrayToBST(arr,0,n-1); inOrder(root); return 0; }

OUTPUT:
2 4 5 6 7 10 11 15

Our inorder traversal prints elements in sorted order, so our binary search tree is correct.
Time Complexity

T(n) = 2T(n/2) + C
By Master Theorem
T(n) = O(n)

Popular posts from this blog

Introduction to Java Security

Introduction to Java Security The Java security architecture includes a large set of application programming interfaces (APIs), tools, and implementations of commonly-used security algorithms, mechanisms, and protocols. The Java security APIs span a wide range of areas. Cryptographic and public key infrastructure (PKI) interfaces provide the underlying basis for developing secure applications. Interfaces for performing authentication and access control enable applications to guard against unauthorized access to protected resources. The JDK includes a number of providers that implement a core set of security services. It also allows for additional custom providers to be installed. This enables developers to extend the platform with new security mechanisms. The JDK is divided into modules. Modules that contain security APIs include the following:

Module Description java.base Defines the foundational APIs of Java SE;  contained packages include java.securityjavax.cryptojavax.net.ssl,  and…

SQL Injection

Overview A SQL injection attack consists of insertion or "injection" of a SQL query via the input data from the client to the application. A successful SQL injection exploit can read sensitive data from the database, modify database data (Insert/Update/Delete), execute administration operations on the database (such as shutdown the DBMS), recover the content of a given file present on the DBMS file system and in some cases issue commands to the operating system. SQL injection attacks are a type of injection attack, in which SQL commands are injected into data-plane input in order to effect the execution of predefined SQL commands. Threat ModelingSQL injection attacks allow attackers to spoof identity, tamper with existing data, cause repudiation issues such as voiding transactions or changing balances, allow the complete disclosure of all data on the system, destroy the data or make it otherwise unavailable, and become administrators of the database server.SQL Injection is ve…

Insertion Node in the Linkelist.

In this post, methods to insert a new node in linked list are discussed. A node can be added in three ways
1) At the front of the linked list
2) After a given node.
3) At the end of the linked list
public class Linkedlist { Node head; class Node{ int data; Node next; Node(int d){ data =d; next=null; } } // INSERT THE NODE AT THE BEGIN OF LINKEDLIST. public void insertAtfront(int new_data){ // Node temp = head; Node new_node = new Node(new_data); new_node.next = head; head = new_node; }  // INSERT THE NODE AT THE GIVEN POSITION IN LINKEDLIST.
public void insertAtGiven(Node prev_node,int new_data) { if(prev_node == null){ System.out.print("previous node can't be null"); return; } Node new_node = new Node(new_data); new_node.next = prev_node.next; prev_node.next = new_node; } // INSERT THE NODE  AT THE END OF THE LINKEDLIST.   public void insertAtEnd(int new_data){ Node new_node = new Node(new_data); new_node.nex…