#K71537. Lowest Common Ancestor in a Binary Search Tree

    ID: 33553 Type: Default 1000ms 256MiB

Lowest Common Ancestor in a Binary Search Tree

Lowest Common Ancestor in a Binary Search Tree

You are given a binary search tree (BST) constructed by inserting nodes one by one. The BST has the usual properties: for any node, all keys in its left subtree are less than its key and all keys in its right subtree are greater than its key. You are also given two integer values, \(A\) and \(B\). Your task is to determine the lowest common ancestor (LCA) of the two nodes with these values. Formally, if the BST is represented by its root \(r\), and the LCA of nodes \(A\) and \(B\) is defined as the deepest node \(x\) such that both \(A\) and \(B\) are in the subtree of \(x\), then you are required to output \(x\)'s value.

Note: It is guaranteed that both \(A\) and \(B\) exist in the BST constructed from the input sequence.

inputFormat

The input is given via standard input (stdin) in the following format:

  1. The first line contains an integer n representing the number of nodes to be inserted into the BST.
  2. The second line contains n space-separated integers representing the keys. The BST is constructed by inserting these keys one by one in the given order.
  3. The third line contains two space-separated integers A and B for which you are to find the LCA.

outputFormat

Output a single integer representing the value of the lowest common ancestor of the nodes with values A and B in the BST. The output should be written to standard output (stdout).

## sample
7
5 3 8 2 4 7 9
2 7
5

</p>