# Lowest Common Ancestor in a Binary Search Tree.

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).

Example:

Lowest-Common-Ancestor-BST

Input: A binary Search Tree and two nodes n1 and n2.

Appraoch:

1. Start will the root.
2. If root>n1 and root>n2 then lowest common ancestor will be in left subtree.
3. If root<n1 and root<n2 then lowest common ancestor will be in right subtree.
4. If Step 2 and Step 3 is false then we are at the root which is lowest common ancestor, return it.

LCA-in-Binary-Search-Tree

Complete Code:

Output:

```Recursive-Lowest Common Ancestor of Nodes 5 and 14 is : 10
Iterative-Lowest Common Ancestor of Nodes 5 and 14 is : 10
```

__________________________________________________
Top Companies Interview Questions..-

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

### 1 Response

1. eva says:

why (root.data <= n1.data) in the els if statement rather than (root.data < n1.data)

This site uses Akismet to reduce spam. Learn how your comment data is processed.