Balance by Elimination
Time limit3sMemory limit2048 MB
Given a binary tree, the task is to remove at most one leaf so the tree becomes height-balanced, and print the leaf or report balanced or impossible.
Problem
You are given a binary tree with nodes, numbered from to . Node is the root.
The height of the subtree rooted at node is . If a child does not exist, its subtree height is . A leaf has height .
A node is height-balanced if . A binary tree is height-balanced if every node is height-balanced.
Remove at most one leaf so that the tree becomes height-balanced, or report that this is impossible. For example, the tree in the second sample (Figure B.1) becomes balanced after removing node .
Input
The first line contains a single integer (), the number of nodes. Then lines follow. The -th line contains the labels of the left and right child of node . A missing child is written as . The input is guaranteed to be a binary tree.
Output
If the tree is already balanced, print "balanced". If it cannot be made height-balanced, print "impossible". Otherwise, print the number of the leaf to remove.
Hint

Figure B.1: Visualization of Sample Input 2.