Under construction

Still being built. Things may change

Balance by Elimination

Time limit3sMemory limit2048 MB

Summary
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.
Level

Medium6 of 10

Topics
Tree, DFS, Greedy
Solved
No attempts yet

Problem

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

The height of the subtree rooted at node uu is hu=1+max⁡(hleft child,hright child)h_u = 1 + \max(h_{\text{left child}}, h_{\text{right child}}). If a child does not exist, its subtree height is 00. A leaf has height 11.

A node is height-balanced if ∣hleft child−hright child∣<2|h_{\text{left child}} - h_{\text{right child}}| < 2. 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 55.

Input

The first line contains a single integer nn (1≤n≤1051 \le n \le 10^5), the number of nodes. Then nn lines follow. The ii-th line contains the labels of the left and right child of node ii. A missing child is written as 00. 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.

Examples3

  1. Example 1

    Input
    4
    4 2
    0 0
    0 0
    0 3
    
    Expected output
    balanced
    
  2. Example 2

    Input
    5
    2 3
    0 0
    0 4
    0 5
    0 0
    
    Expected output
    5
    
  3. Example 3

    Input
    4
    2 0
    3 0
    4 0
    0 0
    
    Expected output
    impossible