diff --git a/Advanced/C++/BST.cpp b/Advanced/C++/BST.cpp new file mode 100644 index 0000000..1727de4 --- /dev/null +++ b/Advanced/C++/BST.cpp @@ -0,0 +1,41 @@ +//SakhinetiPraveena +//Given array 1 2 3 4 5, code for constructing a balanced binary search tree . +#include +using namespace std; + +struct Node{ + int data; + Node *left,*right; + Node(int val){ + data=val; + left=NULL; + right=NULL; + } +}; +// As the given array is sorted, to construct balanced BST the mid element is taken as root + +Node* ConstructBST(int arr[],int start, int end_){ + if(start>end_) return NULL; + int mid=(start+end_)/2; + Node * root=new Node(arr[mid]); + root->left=ConstructBST(arr,start,mid-1); + root->right=ConstructBST(arr,mid+1,end_); + return root; +} + +// function to print the inorder of BST +void print_inorder(Node* root){ + if(root==NULL) return; + if (root != NULL){ + print_inorder(root->left); + cout << root->data <<" "; + print_inorder(root->right); + } +} + +int main(){ + int arr[5]={1,2,3,4,5}; + Node* root=ConstructBST(arr,0,4); + cout<<"Inorder for the BST is :"; + print_inorder(root); +} diff --git a/Intermediate/C++/BinarySearch.cpp b/Intermediate/C++/BinarySearch.cpp new file mode 100644 index 0000000..2be4ae8 --- /dev/null +++ b/Intermediate/C++/BinarySearch.cpp @@ -0,0 +1,28 @@ +//SakhinetiPraveena +//Binary Search for 3 in 2 4 8 9 1 3 6 + +#include +using namespace std; + +void binarySearch(int arr[], int key,int n){ + int s=0,e=n-1; + while(s<=e){ + int mid=(s+e)/2; + if(arr[mid]==key){ + cout<