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.