PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#LCA0000066. Tổ tiên chung của các lá sâu nhất (LCA of Deepest Leaves)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Tổ tiên chung của các lá sâu nhất (LCA of Deepest Leaves)

LCA of Deepest Leaves

Source: LeetCode

Version: Phuoc Hung OJ Extended

Problem Statement

You are given a rooted binary tree with nn vertices. A leaf has neither a left nor a right child. Depth is the number of edges from the root. Consider all leaves attaining the maximum depth in the entire tree and output their lowest common ancestor. If there is only one deepest leaf, that leaf is the answer. The PHOJ interface represents the binary tree by explicit left/right child indices instead of LeetCode TreeNode objects.

Input

First line: nn and root. For each vertex i=1..ni=1..n, read Li,RiL_i,R_i, the left and right child indices; 00 means no child.

Output

Print the index of the LCA of all deepest leaves.

Subtasks

General constraints: 1≤n≤1051\le n\le 10^5; 1≤root≤n1\le root\le n; 0≤Li,Ri≤n0\le L_i,R_i\le n; các chỉ số con khác 00 tạo thành đúng một cây nhị phân; không một đỉnh nào có hai cha.

  • Subtask 1 (20 points): 1≤n≤401\le n\le 40.

  • Subtask 2 (30 points): 1≤n≤10001\le n\le 1000.

  • Subtask 3 (50 points): 1≤n≤1000001\le n\le 100000.

Examples

Input

5 1
2 3
4 5
0 0
0 0
0 0

Output

2

Explanation

The deepest leaves are 44 and 55 at depth 22; their LCA is vertex 22.