Objective: - Find the Lowest Common Ancestor of two given nodes in a Binary Search Tree
What is Lowest Common Ancestor
In a given binary tree, The lowest common ancestor of two nodes n1 and n2 will be a node X such that node X will be the lowest node who has n1 and n2 as its descendants.
Similar Problem: Lowest Common Ancestor in a Binary Tree ( Not Binary Search Tree).
Input: A binary Search Tree and two nodes n1 and n2.
- Start will the root.
- If root>n1 and root>n2 then lowest common ancestor will be in left subtree.
- If root<n1 and root<n2 then lowest common ancestor will be in right subtree.
- If Step 2 and Step 3 is false then we are at the root which is lowest common ancestor, return it.
Recursive-Lowest Common Ancestor of Nodes 5 and 14 is : 10 Iterative-Lowest Common Ancestor of Nodes 5 and 14 is : 10