Rotate to Root
Time limit1sMemory limit128 MB
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 is accessed. While is not the root, the following step is repeated:
- If is the left child of its parent , perform a right rotation. Let be 's right child. Then takes 's place (so 's former parent, if any, becomes 's parent), becomes 's right child, and becomes 's left child. 's left child and 's right child are unchanged.
- If is the right child of its parent , perform a left rotation. Let be 's left child. Then takes 's place, becomes 's left child, and becomes 's right child. 's right child and 's left child are unchanged.
Each rotation moves one level closer to the root while preserving the in-order sequence of the nodes; after enough rotations 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 , and a non-empty tree whose root has subtrees and has height .
Given a binary tree, determine, for every node , the height the tree would have after is rotated to the root.
Input
The input contains several test cases. The first line of a test case is an integer , the number of nodes, with .
Each of the next lines contains two integers; line gives and , the left and right children of node . A value of means that child is the empty tree; otherwise . The input is guaranteed to describe a valid binary tree.
A line containing a single follows the last test case; it is a terminator and must not be processed.
Output
For each test case output lines; line is the height of the tree after node is rotated to the root.