Rotate to Root

Time limit1sMemory limit128 MB

Summary
Given a binary tree, compute the height of the tree after each node is rotated to the root one at a time.
Level

Hard8 of 10

Topics
Tree, DFS, Dynamic programming, Recursion
Solved
No attempts yet

Problem

Rotate-to-root is a heuristic for balancing binary search trees. The values stored in the tree are irrelevant here; we only care about how the heuristic changes the tree's shape.

A binary tree is either empty or a node with a left child and a right child, each of which is itself a binary tree. No node has more than one parent and there are no cycles, so a non-empty tree has exactly one node with no parent, called the root.

The heuristic is triggered when some node XX is accessed. While XX is not the root, the following step is repeated:

  • If XX is the left child of its parent PP, perform a right rotation. Let BB be XX's right child. Then XX takes PP's place (so PP's former parent, if any, becomes XX's parent), PP becomes XX's right child, and BB becomes PP's left child. XX's left child and PP's right child are unchanged.
  • If XX is the right child of its parent PP, perform a left rotation. Let BB be XX's left child. Then XX takes PP's place, PP becomes XX's left child, and BB becomes PP's right child. XX's right child and PP's left child are unchanged.

Each rotation moves XX one level closer to the root while preserving the in-order sequence of the nodes; after enough rotations XX becomes the root.

The height of a binary tree is the number of nodes on the longest path from the root to a leaf. Formally, the empty tree has height 00, and a non-empty tree whose root has subtrees AA and BB has height 1+max⁡(height(A),height(B))1 + \max(\mathrm{height}(A), \mathrm{height}(B)).

Given a binary tree, determine, for every node XX, the height the tree would have after XX is rotated to the root.

Input

The input contains several test cases. The first line of a test case is an integer NN, the number of nodes, with 1≤N≤1051 \le N \le 10^5.

Each of the next NN lines contains two integers; line ii gives lil_i and rir_i, the left and right children of node ii. A value of 00 means that child is the empty tree; otherwise 1≤li,ri≤N1 \le l_i, r_i \le N. The input is guaranteed to describe a valid binary tree.

A line containing a single 00 follows the last test case; it is a terminator and must not be processed.

Output

For each test case output NN lines; line ii is the height of the tree after node ii is rotated to the root.

Examples3

  1. Example 1

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

    Input
    1
    0 0
    0
    
    Expected output
    1
    
  3. Example 3

    Input
    7
    2 3
    4 5
    6 7
    0 0
    0 0
    0 0
    0 0
    0
    
    Expected output
    3
    4
    4
    4
    4
    4
    4