problems / 193

Lowest Common Ancestor of Two Keys

easy binary-search-tree lca trees 1000 ms · 256 MB

Lowest Common Ancestor of Two Keys

A binary search tree is given as n nodes, each with a key value and references to its left and right children. Find the lowest common ancestor (LCA) of two given keys in the tree.

The LCA of two nodes is the deepest node that is an ancestor of both. If one key is not in the tree, return -1. If both keys are equal, their LCA is that key itself (it is its own ancestor).

Input

The first line contains n (1 ≤ n ≤ 10^5), the number of nodes in the BST.

The next n lines each describe a node in the format: key left_child right_child

where key is a unique integer (0 ≤ key ≤ 10^9), and left_child and right_child are the keys of the left and right children (or -1 if no child exists). The first node given is the root of the BST.

The next line contains two space-separated integers k1 and k2 (0 ≤ k1, k2 ≤ 10^9), the keys whose LCA is to be found.

Output

Print the key of the lowest common ancestor of k1 and k2. If either key is not in the tree, print -1.

Notes

The BST property holds: for any node with key v, all keys in its left subtree are strictly less than v, and all keys in its right subtree are strictly greater than v.

Example 1

Input

5
10 5 15
5 3 7
15 -1 -1
3 -1 -1
7 -1 -1
5 15

Output

10

Example 2

Input

7
50 25 75
25 10 35
75 60 90
10 -1 -1
35 -1 -1
60 -1 -1
90 -1 -1
10 35

Output

25

Hints · reveal one at a time if you're stuck

Hint 1

Use the BST ordering: if both keys are smaller than a node's key, where can their LCA be? What if they lie on opposite sides of a node?

Hint 2

Start at the root and walk down. Go left when both keys are smaller than the current key, go right when both are larger, and stop at the first node that does not satisfy either, since that node is the answer.

Hint 3

Before answering, make sure both keys actually appear in the tree, for example by storing the nodes in a map keyed by value. If either key is missing, the output is -1.

report an issue Prefer your own editor? sooks prep 193 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.