Compress a Binary Tree into an integer diagonally
Given a Binary Tree consisting of N nodes, the task is to first compress the tree diagonally to get a list of integers and then, again compress the list to get a single integer using the following operations:
- When a tree is compressed diagonally, its value in binary representation gets compressed.
- Consider each bit position of each node value present in a diagonal. If a position has S set bits and NS non-set bits, then set the bit for that position only if S is greater than NS. Otherwise, unset the bit for that position.
- Compress each diagonal to convert the tree into a list. Then, compress each array element into a single integer by using the same process.
Example: If 7, 6, 3 and 4 gets compressed, then their binary representations, i.e. (111)2, (110)2, (011)2 and (100)2 gets compressed. For the 0th position, S ≤ NS and for the 1st and 2nd positions, S > NS.
Therefore, the number becomes (110)2 = 6.
/ \ / \
3 5 3 4
Diagonal 1: Compress( 6, 3, 4 ) = 6
Diagonal 2: Compress( 5, 5, 3 ) = 5
Diagonal 3: Compress( 3 ) = 3
Finally, compress the list (6, 5, 3) to get 7.
Approach: The idea is to use a Hashmap to store all the nodes which belong to a particular diagonal of the tree. Follow the steps below to solve the problem:
- For the diagonal traversal of the tree, keep track of the horizontal distance from the root node for each node.
- Use a Hashmap to store the elements belonging to the same diagonal.
- After the traversal, count the number of set bits for each position for each diagonal of the tree and set the bit for the positions where the number of set bits exceeds the number of unset bits.
- Store the compressed value of each diagonal in an array.
- After obtaining the array, apply the same steps for compression to obtain the required integer.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.