Lowest common ancestor of a BST

The lowest common ancestor (LCA) of two nodes xx and yy in a tree is the lowest (i.e. deepest) node that has both xx and yy as descendants, where we define each node to be a descendant of itself.

For instance, in the following tree, 5 is the LCA of 1 and 9, and 6 is the LCA of 1 and 0:

image

Write a function @Tree lowest_common_ancestor_bst (Tree t, int x, int y);@ that returns the
node that corresponds to the LCA of xx and yy in a binary search tree of integers tt. You can assume that tt is a binary search tree and that tt contains both xx and yy. Note that an efficient solution is expected, exploiting the fact that the tree is a binary search tree.

Most of the program is already writen for you. Download it! It reads several binary search trees in preorder (empty trees are marked with a 1-1 value) and, for each of these, reads severals pairs of values and prints their LCA. You just have to specify and implement the @lowest_common_ancestor_bst()@ function (and other helper functions, should you need them). Also, write a comment with the time efficiency of your algorithm.

Problem information

Author: Jordi Petit

Generation: 2026-01-25T11:12:34.966Z

© Jutge.org, 2006–2026.
https://jutge.org