Open in App
Not now

# Create a balanced BST using vector in C++ STL

• Difficulty Level : Easy
• Last Updated : 20 Mar, 2023

Given an unsorted vector arr, the task is to create a balanced binary search tree using the elements of the array.

Note: There can be more than one balanced BST. Forming any is acceptable

Examples:

Input: arr[] = { 2, 1, 3}
Output: 2 1 3
Explanation: The tree formed is show below. The preorder traversal is 2 1 3
2
/  \
1    3

Input: arr[] = {4, 3, 1, 2}
Output: 2 1 3 4
Explanation: The tree formed is
2
/  \
1    3
\
4
Another possible option can provide preorder traversal is 3 2 1 4

Approach: To solve this problem, follow the below steps:

1. Firstly, we will sort the vector using the sort function.
2. Now, get the Middle of the vector and make it root.
3. Recursively do the same for the left half and the right half.
1. Get the middle of the left half and make it the left child of the root created in step 2.
2. Get the middle of the right half and make it the right child of the root created in step 2.

Below is the implementation of the above approach:

## C++

 `// C++ program to print BST in given range` `#include ` `using` `namespace` `std;`   `// Node of Binary Search Tree` `class` `Node {` `public``:` `    ``Node* left;` `    ``int` `data;` `    ``Node* right;`   `    ``Node(``int` `d)` `    ``{` `        ``data = d;` `        ``left = right = NULL;` `    ``}` `};`   `// A function that constructs Balanced` `// Binary Search Tree from a vector` `Node* createBST(vector<``int``> v, ``int` `start, ` `                ``int` `end)` `{` `    ``sort(v.begin(), v.end());`   `    ``// Base Case` `    ``if` `(start > end)` `        ``return` `NULL;`   `    ``// Get the middle element and make it root` `    ``int` `mid = (start + end) / 2;` `    ``Node* root = ``new` `Node(v[mid]);`   `    ``// Recursively construct the left subtree` `    ``// and make it left child of root` `    ``root->left = createBST(v, start, mid - 1);`   `    ``// Recursively construct the right subtree` `    ``// and make it right child of root` `    ``root->right = createBST(v, mid + 1, end);`   `    ``return` `root;` `}`   `vector<``int``> preNode, vec;`   `// A utility function to print` `// preorder traversal of BST` `vector<``int``> preOrder(Node* node)` `{` `    ``// Root Left Right` `    ``if` `(node == NULL) {` `        ``return` `vec;` `    ``}` `    ``preNode.push_back(node->data);` `    ``preOrder(node->left);` `    ``preOrder(node->right);` `    ``return` `preNode;` `}`   `// Driver Code` `int` `main()` `{` `    ``vector<``int``> v = { 4, 3, 1, 2 };` `    ``Node* root = createBST(v, 0, v.size() - 1);`   `    ``vector<``int``> ans = preOrder(root);` `    ``for` `(``auto` `i : ans) {` `        ``cout << i << ``" "``;` `    ``}` `    ``return` `0;` `}`

## Java

 `// Java program for the above approach`   `import` `java.util.*;`   `// Node of Binary Search Tree` `class` `Node {` `    ``Node left;` `    ``int` `data;` `    ``Node right;`   `    ``Node(``int` `d) {` `        ``data = d;` `        ``left = right = ``null``;` `    ``}` `}`   `class` `Main {` `    ``static` `List preNode = ``new` `ArrayList<>();` `    ``static` `List vec = ``new` `ArrayList<>();`   `    ``// A function that constructs Balanced` `    ``// Binary Search Tree from a vector` `    ``static` `Node createBST(List v, ``int` `start, ``int` `end) {` `        ``Collections.sort(v);`   `        ``// Base Case` `        ``if` `(start > end)` `            ``return` `null``;`   `        ``// Get the middle element and make it root` `        ``int` `mid = (start + end) / ``2``;` `        ``Node root = ``new` `Node(v.get(mid));`   `        ``// Recursively construct the left subtree` `        ``// and make it left child of root` `        ``root.left = createBST(v, start, mid - ``1``);`   `        ``// Recursively construct the right subtree` `        ``// and make it right child of root` `        ``root.right = createBST(v, mid + ``1``, end);`   `        ``return` `root;` `    ``}`   `    ``// A utility function to print` `    ``// preorder traversal of BST` `    ``static` `List preOrder(Node node) {` `        ``// Root Left Right` `        ``if` `(node == ``null``) {` `            ``return` `vec;` `        ``}` `        ``preNode.add(node.data);` `        ``preOrder(node.left);` `        ``preOrder(node.right);` `        ``return` `preNode;` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `main(String[] args) {` `        ``List v = Arrays.asList(``4``, ``3``, ``1``, ``2``);` `        ``Node root = createBST(v, ``0``, v.size() - ``1``);`   `        ``List ans = preOrder(root);` `        ``for` `(``int` `i : ans) {` `            ``System.out.print(i + ``" "``);` `        ``}` `    ``}` `}`   `// This code is contributed by codebraxnzt`

Output

```PreOrder Traversal of constructed BST
4 2 1 3 6 5 7 ```

Time Complexity: O(N * logN)
Auxiliary Space: O(N) to create the tree

My Personal Notes arrow_drop_up
Related Articles