Balance by Elimination

시간 제한3초메모리 제한2048 MB

요약
이진 트리에서 잎 하나를 제거해 모든 노드가 높이 균형을 이루도록 만들 수 있는지 판단하고, 가능하면 제거할 잎을 찾는다.
난이도

보통10점 중 6점

유형
트리, DFS, 구현
정답자
아직 제출이 없습니다

문제

You are given a binary tree with nn nodes. The nodes are conveniently numbered from 11 to nn. Node 11 is the root of the binary tree.

The height of the subtree rooted at node uu is: h_u=1+max⁡(h_left child,h_right child)h\_u = 1 + \max \left(h\_\textrm{left child}, h\_\textrm{right child}\right) 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 11.

You want the tree to become height-balanced. A node is height-balanced if: ∣h_left child−h_right child∣<2\left|h\_\textrm{left child} - h\_\textrm{right child}\right| < 2 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 55.

입력

The input consists of:

  • One line containing a single integer nn (1≤n≤1051 \leq n \leq 10^5), the number of nodes in the binary tree.
  • Then nn lines follow, numbered from 11 to nn. The iith line contains two integers, the labels of the left and right child of node ii.

If a left child or right child does not exist, the corresponding integer is equal to 00. 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.

예제3

  1. 예제 1

    입력
    4
    4 2
    0 0
    0 0
    0 3
    
    예상 출력
    balanced
    
  2. 예제 2

    입력
    5
    2 3
    0 0
    0 4
    0 5
    0 0
    
    예상 출력
    5
    
  3. 예제 3

    입력
    4
    2 0
    3 0
    4 0
    0 0
    
    예상 출력
    impossible