You are given a binary tree with distinct positive integer values. You can transform this binary tree to a graph by adding connections between any two nodes if they are not already connected. 2 nodes are connected if either of them is a child of the other node.
Your goal is to identify and enumerate the minimum number of connections that need to be drawn between the nodes of this tree so that the resulting graph fully contains the min-heap that can be formed using the value of the nodes.
Write a method that will take as input an array defining the tree. The root of the tree will be at index 0, the left and the right child of the element at the index i will be 2i+1 and 2i+2 respectively. A value of -1 indicates NULL. If an index has no defined left and right child, assume NULL.
The method will enumerate the connections as described above and identify the unique values that the connections must be set up for. For each of the connections, there will be 2 values denoting the ends of the connection to be built – add all of these values into an integer array sorted by the smallest value of the connection and then by larger value.
Function Signature:
class Solution{
public int[] solution(int[] A){
}
}As an example, if you are provided with the following tree:
[ 3, 7, 4, 6, -1, 1, 9 ]

The the resulting graph that contains the min-heap can be formed by adding two connections (1,3) and (3,6). Thereafter the left child of any node is located by following the red arrow from the node and the right child can be similarly located by following the yellow arrow.

Consequently your output should be
[1, 3, 3, 6]
This is because as seen above creating the min-heap will need 2 additional connections between points 1 and 3, and between points 3 and 6. Note that of the two connections (1,3) and (3,6), (1,3) has the smallest value and hence added first. Even during the insertion 1 being the smaller of the two is added first followed by 3.