All problems

Problem 153

Lowest Common Ancestor of a BST

Medium · 20 pts · Tree, Binary Search Tree

Problem

You are given a binary search tree with distinct values and two values P and Q that are both in it. Print the value of their lowest common ancestor: the deepest node that has both P and Q in its subtree. A node counts as being in its own subtree, so if P is an ancestor of Q, the answer is P. Use the search tree property. Starting at the root, if both values are smaller than the current node, go left; if both are larger, go right. Otherwise they split here (or one of them is this node), so the current node is the answer.

Input

First line: integer N, the number of tokens. Second line: N tokens describing the tree in level order, where 'null' marks a missing child (the same format LeetCode uses). Third line: the values P and Q.

Output

Print the value of the lowest common ancestor.

Constraints

2 <= number of nodes <= 100000; values are distinct; P != Q, both present

Example input

11
6 2 8 0 4 7 9 null null 3 5
2 8

Example output

6

Explanation

In the tree rooted at 6, the value 2 is in the left subtree and 8 is in the right subtree. They split at the root, so the lowest common ancestor is 6.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Validate Binary Search Tree Next: Kth Smallest Element in a BST