Lowest Common Ancestor in a Binary Search Tree.

16 Jun, 2022
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. 
Examples: 
Tree: 
Input: LCA of 10 and 14
Output:  12
Explanation: 12 is the closest node to both 10 and 14 
which is a ancestor of both the nodes.

Input: LCA of 8 and 14
Output:  8
Explanation: 8 is the closest node to both 8 and 14 
which is a ancestor of both the nodes.

Input: LCA of 10 and 22
Output:  20
Explanation: 20 is the closest node to both 10 and 22 
which is a ancestor of both the nodes.
Following is the definition of LCA from Wikipedia: 
Let T be a rooted tree. The lowest common ancestor between two nodes n1 and n2 is defined as the lowest node in T that has both n1 and n2 as descendants (where we allow a node to be a descendant of itself).The LCA of n1 and n2 in T is the shared ancestor of n1 and n2 that is located farthest from the root. Computation of lowest common ancestors may be useful, for instance, as part of a procedure for determining the distance between pairs of nodes in a tree: the distance from n1 to n2 can be computed as the distance from the root to n1, plus the distance from the root to n2, minus twice the distance from the root to their lowest common ancestor. (Source Wiki) 
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Approach: For Binary search tree, while traversing the tree from top to bottom the first node which lies in between the two numbers n1 and n2 is the LCA of the nodes, i.e. the first node n with the lowest depth which lies in between n1 and n2 (n1<=n<=n2) n1 < n2. So just recursively traverse the BST in, if node’s value is greater than both n1 and n2 then our LCA lies in the left side of the node, if it’s is smaller than both n1 and n2, then LCA lies on the right side. Otherwise, the root is LCA (assuming that both n1 and n2 are present in BST).
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.
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.
Implementation:  
C++
C
Java
Python3
C#
Javascript
// A recursive CPP program to find// LCA of two nodes n1 and n2.#include <bits/stdc++.h>using namespace std; class node{    public:    int data;    node* left, *right;}; /* Function to find LCA of n1 and n2.The function assumes that bothn1 and n2 are present in BST */node *lca(node* root, int n1, int n2){    if (root == NULL) return NULL;     // If both n1 and n2 are smaller    // than root, then LCA lies in left    if (root->data > n1 && root->data > n2)        return lca(root->left, n1, n2);     // If both n1 and n2 are greater than    // root, then LCA lies in right    if (root->data < n1 && root->data < n2)        return lca(root->right, n1, n2);     return root;} /* Helper function that allocatesa new node with the given data.*/node* newNode(int data){    node* Node = new node();    Node->data = data;    Node->left = Node->right = NULL;    return(Node);} /* Driver code*/int main(){    // Let us construct the BST    // shown in the above figure    node *root = newNode(20);    root->left = newNode(8);    root->right = newNode(22);    root->left->left = newNode(4);    root->left->right = newNode(12);    root->left->right->left = newNode(10);    root->left->right->right = newNode(14);     int n1 = 10, n2 = 14;    node *t = lca(root, n1, n2);    cout << "LCA of " << n1 << " and " << n2 << " is " << t->data<<endl;     n1 = 14, n2 = 8;    t = lca(root, n1, n2);    cout<<"LCA of " << n1 << " and " << n2 << " is " << t->data << endl;     n1 = 10, n2 = 22;    t = lca(root, n1, n2);    cout << "LCA of " << n1 << " and " << n2 << " is " << t->data << endl;    return 0;} // This code is contributed by rathbhupendra
// A recursive C program to find LCA of two nodes n1 and n2.#include <stdio.h>#include <stdlib.h> struct node{    int data;    struct node* left, *right;}; /* Function to find LCA of n1 and n2. The function assumes that both   n1 and n2 are present in BST */struct node *lca(struct node* root, int n1, int n2){    if (root == NULL) return NULL;     // If both n1 and n2 are smaller than root, then LCA lies in left    if (root->data > n1 && root->data > n2)        return lca(root->left, n1, n2);     // If both n1 and n2 are greater than root, then LCA lies in right    if (root->data < n1 && root->data < n2)        return lca(root->right, n1, n2);     return root;} /* Helper function that allocates a new node with the given data.*/struct node* newNode(int data){    struct node* node = (struct node*)malloc(sizeof(struct node));    node->data  = data;    node->left  = node->right = NULL;    return(node);} /* Driver program to test lca() */int main(){    // Let us construct the BST shown in the above figure    struct node *root        = newNode(20);    root->left               = newNode(8);    root->right              = newNode(22);    root->left->left         = newNode(4);    root->left->right        = newNode(12);    root->left->right->left  = newNode(10);    root->left->right->right = newNode(14);     int n1 = 10, n2 = 14;    struct node *t = lca(root, n1, n2);    printf("LCA of %d and %d is %d \n", n1, n2, t->data);     n1 = 14, n2 = 8;    t = lca(root, n1, n2);    printf("LCA of %d and %d is %d \n", n1, n2, t->data);     n1 = 10, n2 = 22;    t = lca(root, n1, n2);    printf("LCA of %d and %d is %d \n", n1, n2, t->data);     getchar();    return 0;}
// Recursive Java program to print lca of two nodes  // A binary tree nodeclass Node{    int data;    Node left, right;      Node(int item)    {        data = item;        left = right = null;    }}  class BinaryTree{    Node root;          /* Function to find LCA of n1 and n2. The function assumes that both       n1 and n2 are present in BST */    Node lca(Node node, int n1, int n2)    {        if (node == null)            return null;          // If both n1 and n2 are smaller than root, then LCA lies in left        if (node.data > n1 && node.data > n2)            return lca(node.left, n1, n2);          // If both n1 and n2 are greater than root, then LCA lies in right        if (node.data < n1 && node.data < n2)            return lca(node.right, n1, n2);          return node;    }      /* Driver program to test lca() */    public static void main(String args[])    {        // Let us construct the BST shown in the above figure        BinaryTree tree = new BinaryTree();        tree.root = new Node(20);        tree.root.left = new Node(8);        tree.root.right = new Node(22);        tree.root.left.left = new Node(4);        tree.root.left.right = new Node(12);        tree.root.left.right.left = new Node(10);        tree.root.left.right.right = new Node(14);          int n1 = 10, n2 = 14;        Node t = tree.lca(tree.root, n1, n2);        System.out.println("LCA of " + n1 + " and " + n2 + " is " + t.data);          n1 = 14;        n2 = 8;        t = tree.lca(tree.root, n1, n2);        System.out.println("LCA of " + n1 + " and " + n2 + " is " + t.data);          n1 = 10;        n2 = 22;        t = tree.lca(tree.root, n1, n2);        System.out.println("LCA of " + n1 + " and " + n2 + " is " + t.data);      }}  // This code has been contributed by Mayank Jaiswal
# A recursive python program to find LCA of two nodes# n1 and n2 # A Binary tree nodeclass Node:     # Constructor to create a new node    def __init__(self, data):        self.data = data        self.left = None        self.right = None # Function to find LCA of n1 and n2. The function assumes# that both n1 and n2 are present in BSTdef lca(root, n1, n2):         # Base Case    if root is None:        return None     # If both n1 and n2 are smaller than root, then LCA    # lies in left    if(root.data > n1 and root.data > n2):        return lca(root.left, n1, n2)     # If both n1 and n2 are greater than root, then LCA    # lies in right    if(root.data < n1 and root.data < n2):        return lca(root.right, n1, n2)     return root # Driver program to test above function # Let us construct the BST shown in the figureroot = Node(20)root.left = Node(8)root.right = Node(22)root.left.left = Node(4)root.left.right = Node(12)root.left.right.left = Node(10)root.left.right.right = Node(14) n1 = 10 ; n2 = 14t = lca(root, n1, n2)print ("LCA of %d and %d is %d" %(n1, n2, t.data)) n1 = 14 ; n2 = 8t = lca(root, n1, n2)print ("LCA of %d and %d is %d" %(n1, n2 , t.data)) n1 = 10 ; n2 = 22t = lca(root, n1, n2)print ("LCA of %d and %d is %d" %(n1, n2, t.data)) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
using System; // Recursive C#  program to print lca of two nodes // A binary tree nodepublic class Node{    public int data;    public Node left, right;     public Node(int item)    {        data = item;        left = right = null;    }} public class BinaryTree{    public Node root;     /* Function to find LCA of n1 and n2. The function assumes that both       n1 and n2 are present in BST */    public virtual Node lca(Node node, int n1, int n2)    {        if (node == null)        {            return null;        }         // If both n1 and n2 are smaller than root, then LCA lies in left        if (node.data > n1 && node.data > n2)        {            return lca(node.left, n1, n2);        }         // If both n1 and n2 are greater than root, then LCA lies in right        if (node.data < n1 && node.data < n2)        {            return lca(node.right, n1, n2);        }         return node;    }     /* Driver program to test lca() */    public static void Main(string[] args)    {        // Let us construct the BST shown in the above figure        BinaryTree tree = new BinaryTree();        tree.root = new Node(20);        tree.root.left = new Node(8);        tree.root.right = new Node(22);        tree.root.left.left = new Node(4);        tree.root.left.right = new Node(12);        tree.root.left.right.left = new Node(10);        tree.root.left.right.right = new Node(14);         int n1 = 10, n2 = 14;        Node t = tree.lca(tree.root, n1, n2);        Console.WriteLine("LCA of " + n1 + " and " + n2 + " is " + t.data);         n1 = 14;        n2 = 8;        t = tree.lca(tree.root, n1, n2);        Console.WriteLine("LCA of " + n1 + " and " + n2 + " is " + t.data);         n1 = 10;        n2 = 22;        t = tree.lca(tree.root, n1, n2);        Console.WriteLine("LCA of " + n1 + " and " + n2 + " is " + t.data);     }}   //  This code is contributed by Shrikant13
<script> // Recursive JavaScript program to print lca of two nodes    // A binary tree nodeclass Node{    constructor(item)    {        this.data=item;        this.left=this.right=null;    }} let root; function lca(node,n1,n2){    if (node == null)            return null;            // If both n1 and n2 are smaller than root,        // then LCA lies in left        if (node.data > n1 && node.data > n2)            return lca(node.left, n1, n2);            // If both n1 and n2 are greater than root,        // then LCA lies in right        if (node.data < n1 && node.data < n2)            return lca(node.right, n1, n2);            return node;} /* Driver program to test lca() */ // Let us construct the BST shown in the above figureroot = new Node(20);root.left = new Node(8);root.right = new Node(22);root.left.left = new Node(4);root.left.right = new Node(12);root.left.right.left = new Node(10);root.left.right.right = new Node(14); let n1 = 10, n2 = 14;let t = lca(root, n1, n2);document.write("LCA of " + n1 + " and " + n2 + " is " +t.data+"<br>"); n1 = 14;n2 = 8;t = lca(root, n1, n2);document.write("LCA of " + n1 + " and " + n2 + " is " +t.data+"<br>"); n1 = 10;n2 = 22;t = lca(root, n1, n2);document.write("LCA of " + n1 + " and " + n2 + " is " +t.data+"<br>"); // This code is contributed by avanitrachhadiya2155 </script>
LCA of 10 and 14 is 12 
LCA of 14 and 8 is 8 
LCA of 10 and 22 is 20 
Complexity Analysis:  
Time Complexity: O(h). The time Complexity of the above solution is O(h), where h is the height of the tree.
Space Complexity: O(h). If recursive stack space is ignored, the space complexity of the above solution is constant.
Iterative Implementation: The above solution uses recursion. The recursive solution requires extra space in the form of the function call stack. So an iterative solution can be implemented which does not occupy space in the form of the function call stack.
Implementation:  
C++
C
Java
Python3
C#
Javascript
// A recursive CPP program to find// LCA of two nodes n1 and n2.#include <bits/stdc++.h>using namespace std; class node{    public:    int data;    node* left, *right;}; /* Function to find LCA of n1 and n2.The function assumes that both n1 and n2are present in BST */node *lca(node* root, int n1, int n2){    while (root != NULL)    {        // If both n1 and n2 are smaller than root,        // then LCA lies in left        if (root->data > n1 && root->data > n2)        root = root->left;         // If both n1 and n2 are greater than root,        // then LCA lies in right        else if (root->data < n1 && root->data < n2)        root = root->right;         else break;    }    return root;}   /* Helper function that allocatesa new node with the given data.*/node* newNode(int data){    node* Node = new node();    Node->data = data;    Node->left = Node->right = NULL;    return(Node);} /* Driver code*/int main(){    // Let us construct the BST    // shown in the above figure    node *root = newNode(20);    root->left = newNode(8);    root->right = newNode(22);    root->left->left = newNode(4);    root->left->right = newNode(12);    root->left->right->left = newNode(10);    root->left->right->right = newNode(14);     int n1 = 10, n2 = 14;    node *t = lca(root, n1, n2);    cout << "LCA of " << n1 << " and " << n2 << " is " << t->data<<endl;     n1 = 14, n2 = 8;    t = lca(root, n1, n2);    cout<<"LCA of " << n1 << " and " << n2 << " is " << t->data << endl;     n1 = 10, n2 = 22;    t = lca(root, n1, n2);    cout << "LCA of " << n1 << " and " << n2 << " is " << t->data << endl;    return 0;} // This code is contributed by rathbhupendra
// A recursive C program to find LCA of two nodes n1 and n2.#include <stdio.h>#include <stdlib.h> struct node{    int data;    struct node* left, *right;}; /* Function to find LCA of n1 and n2. The function assumes that bothn1 and n2 are present in BST */struct node *lca(struct node* root, int n1, int n2){    while (root != NULL)    {        // If both n1 and n2 are smaller than root, then LCA lies in left        if (root->data > n1 && root->data > n2)        root = root->left;         // If both n1 and n2 are greater than root, then LCA lies in right        else if (root->data < n1 && root->data < n2)        root = root->right;         else break;    }    return root;}  /* Helper function that allocates a new node with the given data.*/struct node* newNode(int data){    struct node* node = (struct node*)malloc(sizeof(struct node));    node->data = data;    node->left = node->right = NULL;    return(node);} /* Driver program to test lca() */int main(){    // Let us construct the BST shown in the above figure    struct node *root     = newNode(20);    root->left             = newNode(8);    root->right             = newNode(22);    root->left->left         = newNode(4);    root->left->right     = newNode(12);    root->left->right->left = newNode(10);    root->left->right->right = newNode(14);     int n1 = 10, n2 = 14;    struct node *t = lca(root, n1, n2);    printf("LCA of %d and %d is %d \n", n1, n2, t->data);     n1 = 14, n2 = 8;    t = lca(root, n1, n2);    printf("LCA of %d and %d is %d \n", n1, n2, t->data);     n1 = 10, n2 = 22;    t = lca(root, n1, n2);    printf("LCA of %d and %d is %d \n", n1, n2, t->data);     getchar();    return 0;}
// Recursive Java program to print lca of two nodes // A binary tree nodeclass Node{    int data;    Node left, right;     Node(int item)    {        data = item;        left = right = null;    }} class BinaryTree{    Node root;     /* Function to find LCA of n1 and n2.The function assumes that bothn1 and n2 are present in BST */static Node lca(Node root, int n1, int n2){    while (root != null)    {        // If both n1 and n2 are smaller        // than root, then LCA lies in left        if (root.data > n1 &&            root.data > n2)        root = root.left;         // If both n1 and n2 are greater        // than root, then LCA lies in right        else if (root.data < n1 &&                 root.data < n2)        root = root.right;         else break;    }    return root;}      /* Driver program to test lca() */    public static void main(String args[])    {        // Let us construct the BST shown in the above figure        BinaryTree tree = new BinaryTree();        tree.root = new Node(20);        tree.root.left = new Node(8);        tree.root.right = new Node(22);        tree.root.left.left = new Node(4);        tree.root.left.right = new Node(12);        tree.root.left.right.left = new Node(10);        tree.root.left.right.right = new Node(14);         int n1 = 10, n2 = 14;        Node t = tree.lca(tree.root, n1, n2);        System.out.println("LCA of " + n1 + " and " + n2 + " is " + t.data);         n1 = 14;        n2 = 8;        t = tree.lca(tree.root, n1, n2);        System.out.println("LCA of " + n1 + " and " + n2 + " is " + t.data);         n1 = 10;        n2 = 22;        t = tree.lca(tree.root, n1, n2);        System.out.println("LCA of " + n1 + " and " + n2 + " is " + t.data);     }}// This code is contributed by SHUBHAMSINGH10
# A recursive python program to find LCA of two nodes# n1 and n2 # A Binary tree nodeclass Node:     # Constructor to create a new node    def __init__(self, data):        self.data = data        self.left = None        self.right = None # Function to find LCA of n1 and n2.# The function assumes that both#   n1 and n2 are present in BSTdef lca(root, n1, n2):    while root:        # If both n1 and n2 are smaller than root,        # then LCA lies in left        if root.data > n1 and root.data > n2:            root = root.left                 # If both n1 and n2 are greater than root,        # then LCA lies in right        elif root.data < n1 and root.data < n2:            root = root.right         else:            break     return root # Driver program to test above function# Let us construct the BST shown in the figureroot = Node(20)root.left = Node(8)root.right = Node(22)root.left.left = Node(4)root.left.right = Node(12)root.left.right.left = Node(10)root.left.right.right = Node(14) n1 = 10 ; n2 = 14t = lca(root, n1, n2)print ("LCA of %d and %d is %d" %(n1, n2, t.data)) n1 = 14 ; n2 = 8t = lca(root, n1, n2)print ("LCA of %d and %d is %d" %(n1, n2 , t.data)) n1 = 10 ; n2 = 22t = lca(root, n1, n2)print ("LCA of %d and %d is %d" %(n1, n2, t.data))# This Code is Contributed by Sumit Bhardwaj (Timus)
using System; // Recursive C# program to print lca of two nodes // A binary tree nodepublic class Node{    public int data;    public Node left, right;     public Node(int item)    {        data = item;        left = right = null;    }} public class BinaryTree{    public Node root; /* Function to find LCA of n1 and n2.The function assumes that bothn1 and n2 are present in BST */public virtual Node lca(Node root, int n1, int n2){    while (root != null)    {        // If both n1 and n2 are smaller than        // root, then LCA lies in left        if (root.data > n1 && root.data > n2)        root = root.left;          // If both n1 and n2 are greater than        // root, then LCA lies in right        else if (root.data < n1 && root.data < n2)        root = root.right;          else break;    }    return root;}     /* Driver program to test lca() */    public static void Main(string[] args)    {        // Let us construct the BST shown in the above figure        BinaryTree tree = new BinaryTree();        tree.root = new Node(20);        tree.root.left = new Node(8);        tree.root.right = new Node(22);        tree.root.left.left = new Node(4);        tree.root.left.right = new Node(12);        tree.root.left.right.left = new Node(10);        tree.root.left.right.right = new Node(14);         int n1 = 10, n2 = 14;        Node t = tree.lca(tree.root, n1, n2);        Console.WriteLine(            "LCA of " + n1 + " and " + n2            + " is " + t.data);         n1 = 14;        n2 = 8;        t = tree.lca(tree.root, n1, n2);        Console.WriteLine(            "LCA of " + n1 + " and " + n2            + " is " + t.data);         n1 = 10;        n2 = 22;        t = tree.lca(tree.root, n1, n2);        Console.WriteLine(            "LCA of " + n1 + " and " + n2            + " is " + t.data);    }} // This code is contributed by Shrikant13
<script> // Recursive Javascript program to// print lca of two nodes // A binary tree nodeclass Node{    constructor(item)    {        this.data = item;        this.left = null;        this.right = null;    }} var root = null; /* Function to find LCA of n1 and n2.The function assumes that bothn1 and n2 are present in BST */function lca(root, n1, n2){    while (root != null)    {                 // If both n1 and n2 are smaller than        // root, then LCA lies in left        if (root.data > n1 && root.data > n2)            root = root.left;          // If both n1 and n2 are greater than        // root, then LCA lies in right        else if (root.data < n1 && root.data < n2)            root = root.right;          else break;    }    return root;} // Driver code // Let us construct the BST shown// in the above figureroot = new Node(20);root.left = new Node(8);root.right = new Node(22);root.left.left = new Node(4);root.left.right = new Node(12);root.left.right.left = new Node(10);root.left.right.right = new Node(14); var n1 = 10, n2 = 14;var t = lca(root, n1, n2);document.write("LCA of " + n1 + " and " + n2 +               " is " + t.data + "<br>"); n1 = 14;n2 = 8;t = lca(root, n1, n2);document.write("LCA of " + n1 + " and " + n2 +               " is " + t.data+ "<br>"); n1 = 10;n2 = 22;t = lca(root, n1, n2);document.write("LCA of " + n1 + " and " + n2 +               " is " + t.data+ "<br>");                // This code is contributed by rrrtnx </script>
LCA of 10 and 14 is 12 
LCA of 14 and 8 is 8 
LCA of 10 and 22 is 20 
Complexity Analysis: 
Time Complexity: O(h). The Time Complexity of the above solution is O(h), where h is the height of the tree.
Space Complexity: O(1). The space complexity of the above solution is constant.
Lowest Common Ancestor in a Binary Search Tree | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersLowest Common Ancestor in a Binary Search Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:27•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=zlTsz-apm4U" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
You may like to see below articles as well:
Lowest Common Ancestor in a Binary Tree
LCA using Parent Pointer
Find LCA in Binary Tree using RMQ
Exercise The above functions assume that n1 and n2 both are in BST. If n1 and n2 are not present, then they may return an incorrect result. Extend the above solutions to return NULL if n1 or n2 or both not present in BST.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
 
shrikanth13
rathbhupendra
bhardwajsumit016
SHUBHAMSINGH10
andrew1234
avanitrachhadiya2155
aneema4536
rrrtnx
volumezero9786
sambitskd3
amartyaghoshgfg
technophpfij
Accolite
Amazon
LCA
MAQ Software
Microsoft
Samsung
Synopsys
Binary Search Tree
Tree
Accolite
Amazon
Microsoft
Samsung
MAQ Software
Synopsys
Binary Search Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
A program to check if a binary tree is BST or not
Find postorder traversal of BST from preorder traversal
Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
Optimal Binary Search Tree | DP-24
Sorted Array to Balanced BST
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
Introduction to Data Structures
Introduction to Tree Data Structure