Marbles on the tree
InterviewTime limit1sMemory limit128 MB
Given a rooted ordered binary tree, find the leaf where the K-th marble stops, where each marble at a two-child node goes to the left if left subtree has at most the right subtree's resting marbles, else right.
- Level
Medium6 of 10
- Topics
- Tree, DFS, Simulation, Binary search
- Solved
- No attempts yet
Problem

A binary tree is a tree in which every node has at most two children. The number drawn inside each node of the picture is the node number.
The binary tree in this problem is rooted at node 1, and the order of the children matters. You cannot swap the left side and the right side of any subtree.
Put one marble on the root. The marble falls by the following process.
- If the node holding the marble has no child, the marble stops there.
- If the node has exactly one child, the marble falls to that child.
- If the node has two children, the marble falls to the left child when the number of marbles already resting in the left subtree is less than or equal to the number of marbles already resting in the right subtree, and to the right child otherwise.
- Repeat the process until the marble stops.
Every marble ends up on a leaf. Marbles are dropped one at a time, and the next marble is put on the root only after the previous one has stopped.
Dropping marbles on the tree in the picture, the first five stop on nodes 2, 4, 2, 5, 2 in that order.
When the tree is small or the marbles are few, plain simulation tells you where each marble stops. The answer has to come out quickly for a large tree with a huge number of marbles as well.
Given a binary tree and , find the number of the node where the -th marble stops.
Input
The first line contains the number of nodes of the binary tree. ()
Each of the next lines contains two integers and . On the -th of these lines, is the left child of node and is the right child of node . If is , node has no left child. If is , node has no right child. A value other than always satisfies .
The last line contains . ()
The given tree is always a valid binary tree, and the root is node 1.
Output
Print the number of the node where the -th marble stops.