#BST0000020. Tổ tiên chung gần nhất trong BST (Lowest Common Ancestor of a Binary Search Tree)
Tổ tiên chung gần nhất trong BST (Lowest Common Ancestor of a Binary Search Tree)
Lowest Common Ancestor of a Binary Search Tree
Source: LeetCode
Version: Phuoc Hung OJ Extended
Problem Statement
Build a BST from the distinct keys in insertion order.
Two different keys and are guaranteed to exist. A node is a common ancestor of and if both target nodes lie in the subtree rooted at . A node is allowed to be a descendant of itself.
The lowest common ancestor (LCA) is the common ancestor with maximum depth, i.e. the lowest such node in the tree.
Print the key stored at the LCA of and .
Input
The first line contains .
The second line contains the distinct keys in insertion order.
The third line contains and .
Output
Print one integer: the key of the LCA of and .
Subtasks
Subtask 1 (20 points): .
Subtask 2 (30 points): .
Subtask 3 (50 points): .
In all subtasks, , all are distinct, , and both and occur in the tree.
Examples
Input
9
6 2 8 0 4 7 9 3 5
2 8
Output
6
Explanation
Key lies in the left subtree of root , while key lies in its right subtree. No node below can have both targets in its subtree.
Therefore their LCA has key .