Balance by Elimination
시간 제한3초메모리 제한2048 MB
이진 트리에서 잎 하나를 제거해 모든 노드가 높이 균형을 이루도록 만들 수 있는지 판단하고, 가능하면 제거할 잎을 찾는다.
문제
You are given a binary tree with nodes. The nodes are conveniently numbered from to . Node is the root of the binary tree.
The height of the subtree rooted at node is: If a left or right child doesn't exist, its subtree height is defined to be 0. In particular, if a node is a leaf, it has a height of .
You want the tree to become height-balanced. A node is height-balanced if: A binary tree is height-balanced if all its nodes are height-balanced.
Find a way to remove at most 1 leaf from the tree, such that the binary tree becomes height-balanced, or output that this is impossible. For example, the tree of the second sample input (visualized in Figure B.1) becomes balanced when removing node .
입력
The input consists of:
- One line containing a single integer (), the number of nodes in the binary tree.
- Then lines follow, numbered from to . The th line contains two integers, the labels of the left and right child of node .
If a left child or right child does not exist, the corresponding integer is equal to . It is guaranteed that the input graph is a binary tree.
출력
Output a single integer:
- If the tree is already balanced, output "
balanced". - If it's impossible to make the tree height-balanced, output "
impossible". - Else, output the number of the leaf you want to remove.
힌트

Figure B.1: Visualization of Sample Input 2.