Editorial for APIO '07 P1 - Mobiles
Submitting an official solution before solving the problem yourself is a bannable offence.
We can define a complete binary tree to be one that has all leaf nodes at the same depth . The figure below depicts a complete binary tree with depth .
We can likewise define a partially complete binary tree to be one in which all leaf nodes are at depth or depth , and where all leaf nodes at depth form a contiguous block at the leftmost end of the tree. One such example is shown below with depth . Note that all complete binary trees are also considered to be partially complete.
This task asks for the smallest number of operations required to transform a given binary tree into a partially complete binary tree. The only operation available is to swap the left and right children of a node. To solve this task, we define the following recursive functions:
- , which returns the height of a subtree, .
- , which returns the fewest number of swaps required to make the subtree complete. This will be if the given subtree is already complete, or otherwise (since if a tree is not already complete, it can never be made complete). To calculate this, we simply check whether the subtree's two immediate children are complete subtrees and whether they have the same height.
- , which returns the fewest number of swaps required to make the given subtree partially complete, or if this is not possible. Let and denote the left and right subtrees of . We calculate by taking the minimum of the following:
- The result of ;
- If , then consider ;
- If , then consider ;
- If , then consider both and .
Each of these functions is calculated recursively for each subtree, working upwards from the leaves to the root of the tree. The final solution has a running time of , where is the number of nodes in the tree.
Comments