Unstop Coding Question – Solved

8 Live
Solution Rahul has an integer array called 'arr' of length N containing unique values. He wants to create a balanced tree where each parent node has smaller valued nodes on its left and larger valued nodes on its right. This balanced tree should ensure that the depth of the two subtrees for every node doesn't differ by more than one. Your task is to assist him in creating this type of tree. The output contains N lines denoting the pre-order traversal of nodes. If the left child of the node contains a non-null value, then print the value; otherwise, print a dot (.). A similar process for the right child also. Each right child value is separated from the node by a ">" sign, and each left child by a left arrow sign. Input Format: - First line contains an integer N representing the size of the array arr. - The second line contains N unique space-separated integers representing the elements of the array arr. Output Format: The output contains N lines denoting the pre-order traversal of nodes. If the left child of the node contains a non-null value, then print the value; otherwise, print a dot (.). A similar process for the right child also. Each right child value is separated from the node by a "-" sign, and each left child by a left arrow sign. Constraints: 1 <= N <= 10^5 1 <= arr[i] <= 10^19

Asked in: Unstop

Image of the Question

Question Image

All Testcases Passed ✔



Passcode Image

Solution


class TreeNode:
    def _init_(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
// ... rest of solution available after purchase

🔒 Please login to view the solution

Explanation


```
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.
```


Related Questions