• Tutorials
  • DSA
  • Data Science
  • Web Tech
  • Courses
July 31, 2024 |25.0K Views

Lowest Common Ancestor in a Binary Search Tree

  Share   Like
Description
Discussion

Given values of two values n1 and n2 in a Binary Search Tree, find the Lowest Common Ancestor (LCA). You may assume that both the values exist in the tree. 


Input: LCA of 10 and 14


Output:  12


Explanation: 12 is the closest node to both 10 and 14 


Algorithm:  

Create a recursive function that takes a node and the two values n1 and n2.


If the value of the current node is less than both n1 and n2, then LCA lies in the right subtree. Call the recursive function for the right subtree.


If the value of the current node is greater than both n1 and n2, then LCA lies in the left subtree. Call the recursive function for the left subtree.


If both the above cases are false then return the current node as LCA.

 

Lowest Common Ancestor in a Binary Search Tree  : https://www.geeksforgeeks.org/lowest-common-ancestor-in-a-binary-search-tree/