25(July) Array to BST
25. Array to BST
The problem can be found at the following link: Question Link
Problem Description
Given a sorted array, convert it into a Height Balanced Binary Search Tree (BST). Return the root of the BST.
A height-balanced BST is a binary tree in which the depth of the left subtree and the right subtree of every node never differ by more than 1.
Note: The driver code will check if the BST is height-balanced. If it is, the output will be true; otherwise, the output will be false.
Example:
Input:
nums = [1, 2, 3, 4]Output:
trueExplanation: The preorder traversal of the following BST formed is [2, 1, 3, 4]:
My Approach
Recursive Helper Function:
Create a helper function
sortedArrayToBSTUtilthat takes the array and the current bounds (leftandright) as arguments.If
leftis greater thanright, returnnullptr(base case for recursion).
Mid Calculation:
Calculate the middle index of the current segment:
mid = left + (right - left) / 2.
Node Creation:
Create a new node with the value at the middle index:
node = new Node(nums[mid]).
Recursive Calls:
Recursively create the left and right subtrees using the helper function:
node->left = sortedArrayToBSTUtil(nums, left, mid - 1)node->right = sortedArrayToBSTUtil(nums, mid + 1, right)
Return:
Return the created node.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), as each element of the array is processed exactly once.
Expected Auxiliary Space Complexity: O(n), as the recursion stack can go as deep as the number of elements in the array.
Code (C++)
Code (Java)
Code (Python)
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated