Create a balanced BST using vector in C++ STL Last Updated : 03 Apr, 2023 Comments Improve Suggest changes Like Article Like Report 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 3Explanation: 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 4Explanation: The tree formed is 2 / \ 1 3 \ 4Another possible option can provide preorder traversal is 3 2 1 4 Approach: To solve this problem, follow the below steps: Firstly, we will sort the vector using the sort function.Now, get the Middle of the vector and make it root.Recursively do the same for the left half and the right half.Get the middle of the left half and make it the left child of the root created in step 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 <bits/stdc++.h> 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<Integer> preNode = new ArrayList<>(); static List<Integer> vec = new ArrayList<>(); // A function that constructs Balanced // Binary Search Tree from a vector static Node createBST(List<Integer> 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<Integer> 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<Integer> v = Arrays.asList(4, 3, 1, 2); Node root = createBST(v, 0, v.size() - 1); List<Integer> ans = preOrder(root); for (int i : ans) { System.out.print(i + " "); } } } // This code is contributed by codebraxnzt C# // C# Program for the above approach using System; using System.Collections.Generic; using System.Linq; // Node of Binary Search Tree class Node { public Node left; public int data; public Node right; public Node(int d) { data = d; left = right = null; } } class MainClass { static List<int> preNode = new List<int>(); static List<int> vec = new List<int>(); // A function that constructs Balanced // Binary Search Tree from a vector static Node createBST(List<int> v, int start, int end) { v.Sort(); // 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; } // A utility function to print // preorder traversal of BST static List<int> 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<int> v = new List<int> { 4, 3, 1, 2 }; Node root = createBST(v, 0, v.Count - 1); List<int> ans = preOrder(root); foreach (int i in ans) { Console.Write(i + " "); } } } // This code is contributed by adityashatmfh OutputPreOrder Traversal of constructed BST 4 2 1 3 6 5 7 Time Complexity: O(N * logN)Auxiliary Space: O(N) to create the tree Comment More infoAdvertise with us Next Article Create a balanced BST using vector in C++ STL A akshitsaxenaa09 Follow Improve Article Tags : Tree Binary Search Tree C++ Algo Geek DSA Algo-Geek 2021 BST STL cpp-vector +5 More Practice Tags : CPPBinary Search TreeSTLTree Similar Reads POTD Solutions | 15 Oct' 23 | Normal BST to Balanced BST View all POTD Solutions Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Binary Search Trees but will also help you build up pro 5 min read Sorted Linked List to Balanced BST Given a Singly Linked List which has data members sorted in ascending order. Construct a Balanced Binary Search Tree which has same data members as the given Linked List. Examples: Input: Linked List 1->2->3Output: A Balanced BST 2 / \ 1 3 Input: Linked List 1->2->3->4->5->6- 15+ min read Sorted Array to Balanced BST Given a sorted array. The task is to convert it into a Balanced Binary Search Tree (BST). Return the root of the BST.Examples: Input: arr[] = {10, 20, 30}Output:Explanation: The above sorted array converted to Balanced Binary Search Tree.Input: arr[] = {1, 2, 3, 4, 5, 6, 7}Output:Explanation: The ab 13 min read vector :: cbegin() and vector :: cend() in C++ STL Vectors are known as dynamic arrays which can change its size automatically when an element is inserted or deleted. This storage is maintained by container. vector::cbegin() The function returns an iterator which is used to iterate container. The iterator points to the beginning of the vector.Iterat 2 min read Using class to implement Vector Quantities in C++ A Vector Quantity is a Quantity which possesses both magnitude as well as direction. Here, magnitude is simply the amount or size of the quantity and direction is where the quantity is headed. For example, consider the statement "Go 20 miles north". In the above statement 20 is the magnitude and Nor 4 min read Initializing Vector using an Existing Vector in C++ STL A vector is a type of container which can store objects of similar data type. Vector acts like a dynamic array where we can insert elements and the size of the array increases depending upon the elements inserted. Syntax: vector<data_structure/type> vector_name(size, item) To know more about v 5 min read How to Erase Duplicates and Sort a Vector in C++? In this article, we will learn how to remove duplicates and sort a vector in C++.The simplest method to remove the duplicates and sort the vector is by using sort() and unique() functions. Letâs take a look at an example:C++#include <bits/stdc++.h> using namespace std; int main() { vector<i 3 min read Check if the Binary Tree contains a balanced BST of size K Given a Binary Tree and a positive integer K. The task is to check whether the Balanced BST of size K exists in a given Binary Tree or not. If it exists then print âYesâ else print âNoâ. Examples: Input: K = 4, Below is the given Tree: 15 / \ 10 26 / \ / \ 5 12 25 40 / / \ 20 35 50 \ 60 Output: Yes 13 min read Find a pair with given sum in a Balanced BST Given a Balanced Binary Search Tree and a target sum, the task is to check if there exist a pair in BST with sum equal to the target sum. Any modification to the Binary Search Tree is not allowed.Input: Output: TrueExplanation: The node with values 15 and 20 form a pair which sum up to give target.T 15+ min read How to Sort a Vector in Descending Order Using STL in C++? Sorting vector in descending order means arranging the elements in such a way that the first element will be largest, and second element will be second largest and so on.In C++, the simplest way to sort the vector in descending order is to by using the sort() function with a custom comparator.C++#in 3 min read Like