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
We can likewise define a partially complete binary tree to be one in which all leaf nodes are at depth
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 .
- The result of
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
Comments