(101). 28.5. BUILD BALANCED BST FROM SORTED ARRAY - anishsingh90/Data_Structure_And_Algorithm_In_Cpp_github.io GitHub Wiki
#include <bits/stdc++.h> using namespace std;
struct Node{ int data; Node *left, *right; Node(int val){ data = val; left = NULL; right = NULL; } };
//Balanced BST for sorted Array Node* sortedArrayToBST(int arr[], int start, int end){ if(start > end){ return NULL; }
int mid = (start + end) / 2;
Node* root = new Node(arr[mid]);
root->left = sortedArrayToBST(arr, start, mid-1);
root->right = sortedArrayToBST(arr, mid+1, end);
}
//preorder function void preorderPrint(Node* root){ if(root == NULL){ return; }
cout << root->data << " ";
preorderPrint(root->left);
preorderPrint(root->right);
}
int main(){ int arr[] = {10,20,30,40,50}; Node* root = sortedArrayToBST(arr, 0, 4); cout << "Balanced BST is: "; preorderPrint(root); cout << endl;
return 0;
}
/* OUTPUT: Balanced BST is: 30 10 20 40 50 */