Asked in: Unstop
class TreeNode:
def _init_(self, val=0, left=None, right=None):
self.val = val
self.left = left
// ... rest of solution available after purchase
```
To solve this problem, you need to understand how to construct a balanced binary search tree (BST) from a given array of unique integers, and then print the tree nodes in a specific pre-order traversal format with indications of left and right children.
1. Understanding the Requirements:
The problem asks you to create a balanced BST from the unique values in the array. A BST property is that for each node:
- All values in the left subtree are smaller than the node.
- All values in the right subtree are larger than the node.
The "balanced" requirement means that for every node, the height difference between its left and right subtrees is at most 1. This ensures the tree is height-balanced and helps maintain efficient operations (like search).
After building the tree, you need to print the pre-order traversal. Pre-order traversal means:
- Visit the root node first.
- Traverse the left subtree in pre-order.
- Traverse the right subtree in pre-order.
When printing each node, you also print the values of its left and right children. If a child does not exist, print a dot ('.') instead. The left child is printed with a left arrow '<-' and the right child with a greater than sign '>'. For example:
NodeValue <- LeftChildValue -> RightChildValue
If a child is missing:
NodeValue <- . -> RightChildValue
or
NodeValue <- LeftChildValue -> .
2. Key Insights:
- The tree must be a BST, so the in-order traversal of the tree corresponds exactly to the sorted order of the array elements.
- To maintain balance, the tree should be constructed in such a way that the root is the middle element of the sorted array. This ensures approximately equal nodes on both left and right subtrees.
- Recursively apply this idea to left and right subarrays to build left and right subtrees, respectively.
- Since the array is unsorted initially, you will first need to sort it to find the middle element easily.
- This approach naturally creates a balanced BST because at every recursive step, the chosen root divides the array into nearly equal halves.
3. Approach to Build the Tree:
- Sort the input array.
- Define a recursive function that takes start and end indices of the current subarray.
- Find the middle index of the current subarray.
- Create a node with the middle element as the root.
- Recursively build the left subtree from the left half of the subarray (start to mid-1).
- Recursively build the right subtree from the right half of the subarray (mid+1 to end).
- Return the node.
This recursion terminates when the start index goes beyond the end index (empty subarray), which means the current node has no child in that direction.
4. Printing the Tree:
- After building the tree, perform a pre-order traversal.
- For each visited node:
- Print the node’s value.
- Check if left child exists:
- If yes, print "<- LeftChildValue"
- Else, print "<- ."
- Check if right child exists:
- If yes, print "-> RightChildValue"
- Else, print "-> ."
- Move recursively to the left and right children and repeat.
5. Handling Large Inputs:
- Since N can be up to 10^5 and values can be very large (up to 10^19), use appropriate data types to store the integers.
- The sorting operation will take O(N log N), which is feasible for 10^5 elements.
- The recursive tree-building and traversal are both O(N) operations.
- Use efficient data structures and avoid unnecessary copying of arrays during recursion; pass indices to represent subarrays instead.
6. Edge Cases:
- When N = 1, the tree has only one node with no children, so print the value with both children as '.'.
- When the array is already sorted or reverse sorted, the method still works because it relies on sorting and choosing middle elements.
- All elements are unique, so no duplicate handling is required.
7. Summary:
- Sort the array to have elements in ascending order.
- Recursively build a balanced BST by choosing the middle element as root for subarrays.
- Print the tree nodes in pre-order traversal with the specified format indicating left and right children or '.' if missing.
- This method guarantees a balanced BST and fulfills the problem’s printing requirements efficiently.
By carefully following these steps, you can construct the balanced BST and produce the correct output for large inputs.
```