Saturday, November 16, 2024
Google search engine
HomeData Modelling & AILowest Common Ancestor in a Binary Search Tree.

Lowest Common Ancestor in a Binary Search Tree.

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

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 [i.e., closest to n1 and n2].

Examples: 

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

Lowest Common Ancestor in a Binary Search Tree using Recursion:

To solve the problem follow the below idea:

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 , if node’s value is greater than both n1 and n2 then our LCA lies in the left side of the node, if it 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)

Follow the given steps to solve the problem:

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

Below is the implementation of the above approach.

C++




// 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 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 allocates
a 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);
 
      // Function calls
    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


C




// 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 code */
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);
 
      // Function calls
    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;
}


Java




// Recursive Java program to print lca of two nodes
 
// A binary tree node
class 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 code */
    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);
 
          // Function calls
        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


Python3




# A recursive python program to find LCA of two nodes
# n1 and n2
 
# A Binary tree node
 
 
class 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 BST
 
 
def 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
 
 
# Driver code
root = 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)
 
 
# Function calls
n1 = 10
n2 = 14
t = lca(root, n1, n2)
print("LCA of %d and %d is %d" % (n1, n2, t.data))
 
n1 = 14
n2 = 8
t = lca(root, n1, n2)
print("LCA of %d and %d is %d" % (n1, n2, t.data))
 
n1 = 10
n2 = 22
t = 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)


C#




// Recursive C# program to print lca of two nodes
 
using System;
 
// Recursive C#  program to print lca of two nodes
 
// A binary tree node
public 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 code */
    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);
 
          // Function calls
        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


Javascript




<script>
 
// Recursive JavaScript program to print lca of two nodes
    
// A binary tree node
class 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 figure
root = 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>


Output

LCA of 10 and 14 is 12 
LCA of 14 and 8 is 8 
LCA of 10 and 22 is 20 




Time Complexity: O(H). where H is the height of the tree.
Auxiliary Space: O(H), If recursive stack space is ignored, the space complexity of the above solution is constant.

Below is the iterative implementation of the above approach:

C++




// 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 n2
are 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 allocates
a 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);
 
      // Function calls
    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


C




// 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)
{
    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 code */
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);
 
    // Function calls     
    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;
}


Java




// Recursive Java program to print lca of two nodes
 
// A binary tree node
class 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 */
    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 code */
    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);
 
          // Function calls
        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


Python3




# A recursive python program to find LCA of two nodes
# n1 and n2
 
# A Binary tree node
 
 
class 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 BST
 
 
def 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 code
if __name__ == '__main__':
  root = 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)
 
  # Function calls
  n1 = 10
  n2 = 14
  t = lca(root, n1, n2)
  print("LCA of %d and %d is %d" % (n1, n2, t.data))
 
  n1 = 14
  n2 = 8
  t = lca(root, n1, n2)
  print("LCA of %d and %d is %d" % (n1, n2, t.data))
 
  n1 = 10
  n2 = 22
  t = lca(root, n1, n2)
  print("LCA of %d and %d is %d" % (n1, n2, t.data))
# This Code is Contributed by Sumit Bhardwaj (Timus)


C#




// Recursive C# program to print lca of two nodes
 
using System;
 
// Recursive C# program to print lca of two nodes
 
// A binary tree node
public 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 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 code */
    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);
 
          // Function calls
        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


Javascript




<script>
 
// Recursive Javascript program to
// print lca of two nodes
 
// A binary tree node
class 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 both
n1 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 figure
root = 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>


Output

LCA of 10 and 14 is 12 
LCA of 14 and 8 is 8 
LCA of 10 and 22 is 20 




Time Complexity: O(H). where H is the height of the tree
Auxiliary Space: O(1). The space complexity of the above solution is constant.

Lowest Common Ancestor in a Binary Search Tree using Morris traversal:

In the context of finding the lowest common ancestor of two nodes in a binary search tree, we can use the Morris Traversal approach to perform an in-order traversal of the tree while keeping track of the traversal path. During the traversal, we can check if either of the two nodes we are interested in is found, and if so, we return it as the lowest common ancestor.

Follow the steps to implement the above approach:

  1. Initialize a pointer curr to the root of the tree.
  2. While curr is not NULL, do the following:
  3. If curr has no left child, check if curr is either of the two nodes we are interested in. If it is, return curr. Otherwise, move curr to its right child.
  4. If curr has a left child, find the inorder predecessor pre of curr by moving to the rightmost node in the left subtree of curr.
  5. If the right child of pre is NULL, set it to curr and move curr to its left child.
  6. If the right child of pre is curr, set it to NULL and restore the original tree structure. Then check if curr is either of the two nodes we are interested in. If it is, return curr. Otherwise, move curr to its right child.
  7. If the two nodes we are interested in are not found during the traversal, return NULL

Below is the implementation of the above approach:

C++




// C++ code to implement the morris traversal approach
#include<bits/stdc++.h>
using namespace std;
 
struct TreeNode {
    int val;
    TreeNode *left, *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
 
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
    TreeNode* curr = root;
    while (curr != NULL) {
        if (curr->left == NULL) { // if the left subtree is empty, move to the right subtree
            if (curr == p || curr == q) return curr;
            curr = curr->right;
        }
        else {
            TreeNode* pre = curr->left;
            while (pre->right != NULL && pre->right != curr) pre = pre->right; // find the inorder predecessor of the current node
            if (pre->right == NULL) { // if the predecessor's right child is NULL, make it point to the current node
                pre->right = curr;
                curr = curr->left;
            }
            else { // if the predecessor's right child is the current node, restore the tree structure and move to the right subtree
                pre->right = NULL;
                if (curr == p || curr == q) return curr;
                curr = curr->right;
            }
        }
    }
    return NULL;
}
// Driver Code
int main() {
    /*
    Input Tree:
              5
           /    \
         4       6
          \       \
           3       7
                    \
                     8
    */
    TreeNode *root = new TreeNode(5);
    root->left = new TreeNode(4);
    root->left->right = new TreeNode(3);
    root->right = new TreeNode(6);
    root->right->right = new TreeNode(7);
    root->right->right->right = new TreeNode(8);
 
    TreeNode *p = root->left;
    TreeNode *q = root->left->right;
 
    TreeNode *lca1 = lowestCommonAncestor(root, p, q);
    cout <<" LCA of "<<p->val<<" and "<<q->val<<" is "<< lca1->val << endl;
     
     TreeNode  *x = root->right->right;
     TreeNode *y = root->right->right->right;
 
    TreeNode *lca2 = lowestCommonAncestor(root, x, y);
    cout <<" LCA of "<<x->val<<" and "<<y->val<<" is "<< lca2->val << endl;
 
    return 0;
}
// This code is contributed by Veerendra_Singh_Rajpoot


Java




/*package whatever //do not write package name here */
import java.io.*;
 
// Define the TreeNode class
// representing a node in a binary tree.
class TreeNode {
    int val;
    TreeNode left, right;
 
    public TreeNode(int x) {
        val = x;
        left = null;
        right = null;
    }
}
 
// Define the Solution class
// containing the lowestCommonAncestor method.
class Solution {
    // Function to find the lowest common ancestor (LCA)
    // of two nodes in a binary tree.
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        TreeNode curr = root;
        while (curr != null) {
            // If there is no left child,
            // traverse to the right child.
            if (curr.left == null) {
                // Check if the current node is one of the target nodes.
                if (curr == p || curr == q)
                    return curr;
                curr = curr.right;
            } else {
                // If there is a left child, find the in-order predecessor.
                TreeNode pre = curr.left;
                while (pre.right != null && pre.right != curr)
                    pre = pre.right;
                if (pre.right == null) {
                    // Set the right child of the in-order
                    // predecessor to the current node.
                    pre.right = curr;
                    curr = curr.left;
                } else {
                    // Remove the link from the in-order
                    // predecessor to the current node.
                    pre.right = null;
                    // Check if the current node is one of the target nodes.
                    if (curr == p || curr == q)
                        return curr;
                    curr = curr.right;
                }
            }
        }
        return null;
    }
}
 
public class Main {
    public static void main(String[] args) {
        /*
        Input Tree:
                5
            / \
            4  6
            \   \
            3   7
                    \
                    8
        */
        TreeNode root = new TreeNode(5);
        root.left = new TreeNode(4);
        root.left.right = new TreeNode(3);
        root.right = new TreeNode(6);
        root.right.right = new TreeNode(7);
        root.right.right.right = new TreeNode(8);
 
        TreeNode p = root.left;
        TreeNode q = root.left.right;
 
        Solution s = new Solution();
        TreeNode lca1 = s.lowestCommonAncestor(root, p, q);
        System.out.println("LCA of " + p.val + " and " + q.val + " is " + lca1.val);
 
        TreeNode x = root.right.right;
        TreeNode y = root.right.right.right;
 
        TreeNode lca2 = s.lowestCommonAncestor(root, x, y);
        System.out.println("LCA of " + x.val + " and " + y.val + " is " + lca2.val);
    }
}


Python3




class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
 
# Function to find the lowest common ancestor (LCA)
# of two nodes in a binary tree.
def lowestCommonAncestor(root, p, q):
    curr = root
    while curr:
        # If there is no left child,
        # traverse to the right child.
        if curr.left is None:
            # Check if the current node is one of the target nodes.
            if curr == p or curr == q:
                return curr
            curr = curr.right
        else:
            # If there is a left child, find the in-order predecessor.
            pre = curr.left
            while pre.right and pre.right != curr:
                pre = pre.right
            if pre.right is None:
                # Set the right child of the
                # in-order predecessor to the current node.
                pre.right = curr
                curr = curr.left
            else:
                # Remove the link from the in-order
                # predecessor to the current node.
                pre.right = None
                # Check if the current node
                # is one of the target nodes.
                if curr == p or curr == q:
                    return curr
                curr = curr.right
    return None
 
# Driver Code
if __name__ == "__main__":
    """
    Input Tree:
              5
           /    \
         4       6
          \       \
           3       7
                    \
                     8
    """
    root = TreeNode(5)
    root.left = TreeNode(4)
    root.left.right = TreeNode(3)
    root.right = TreeNode(6)
    root.right.right = TreeNode(7)
    root.right.right.right = TreeNode(8)
 
    p = root.left
    q = root.left.right
 
    lca1 = lowestCommonAncestor(root, p, q)
    print(f"LCA of {p.val} and {q.val} is {lca1.val}")
 
    x = root.right.right
    y = root.right.right.right
 
    lca2 = lowestCommonAncestor(root, x, y)
    print(f"LCA of {x.val} and {y.val} is {lca2.val}")


C#




using System;
 
public class TreeNode
{
    public int val;
    public TreeNode left;
    public TreeNode right;
 
    public TreeNode(int x)
    {
        val = x;
        left = null;
        right = null;
    }
}
 
public class Solution
{
    // Function to find the lowest common ancestor (LCA)
    // of two nodes in a binary tree.
    public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q)
    {
        TreeNode curr = root;
        while (curr != null)
        {
            // If there is no left child,
            // traverse to the right child.
            if (curr.left == null)
            {
                // Check if the current node is one of the target nodes.
                if (curr == p || curr == q)
                    return curr;
                curr = curr.right;
            }
            else
            {
                // If there is a left child,
                // find the in-order predecessor.
                TreeNode pre = curr.left;
                while (pre.right != null && pre.right != curr)
                    pre = pre.right;
                if (pre.right == null)
                {
                    // Set the right child of the in-order
                    // predecessor to the current node.
                    pre.right = curr;
                    curr = curr.left;
                }
                else
                {
                    // Remove the link from the in-order
                    // predecessor to the current node.
                    pre.right = null;
                    // Check if the current node
                    // is one of the target nodes.
                    if (curr == p || curr == q)
                        return curr;
                    curr = curr.right;
                }
            }
        }
        return null;
    }
}
 
// Driver code
public class GFG
{
    public static void Main(string[] args)
    {
        /*
        Input Tree:
                5
            / \
            4  6
            \   \
             3   7
                      \
                       8
        */
        TreeNode root = new TreeNode(5);
        root.left = new TreeNode(4);
        root.left.right = new TreeNode(3);
        root.right = new TreeNode(6);
        root.right.right = new TreeNode(7);
        root.right.right.right = new TreeNode(8);
 
        TreeNode p = root.left;
        TreeNode q = root.left.right;
 
        Solution s = new Solution();
        TreeNode lca1 = s.LowestCommonAncestor(root, p, q);
        Console.WriteLine("LCA of " + p.val + " and " + q.val + " is " + lca1.val);
 
        TreeNode x = root.right.right;
        TreeNode y = root.right.right.right;
 
        TreeNode lca2 = s.LowestCommonAncestor(root, x, y);
        Console.WriteLine("LCA of " + x.val + " and " + y.val + " is " + lca2.val);
    }
}


Javascript




class TreeNode {
    constructor(x) {
        this.val = x;
        this.left = null;
        this.right = null;
    }
}
 
// Function to find the lowest common ancestor (LCA)
// of two nodes in a binary tree.
function lowestCommonAncestor(root, p, q) {
    let curr = root;
    while (curr !== null) {
        // If there is no left child,
        // traverse to the right child.
        if (curr.left === null) {
            // Check if the current node is one of the target nodes.
            if (curr === p || curr === q) return curr;
            curr = curr.right;
        } else {
            // If there is a left child,
            // find the in-order predecessor.
            let pre = curr.left;
            while (pre.right !== null && pre.right !== curr) pre = pre.right;
            if (pre.right === null) {
                // Set the right child of the in-order
                // predecessor to the current node.
                pre.right = curr;
                curr = curr.left;
            } else {
                // Remove the link from the in-order
                // predecessor to the current node.
                pre.right = null;
                // Check if the current node is one of the target nodes.
                if (curr === p || curr === q) return curr;
                curr = curr.right;
            }
        }
    }
    return null;
}
 
// Driver Code
/*
Input Tree:
          5
       /    \
     4       6
      \       \
       3       7
                \
                 8
*/
const root = new TreeNode(5);
root.left = new TreeNode(4);
root.left.right = new TreeNode(3);
root.right = new TreeNode(6);
root.right.right = new TreeNode(7);
root.right.right.right = new TreeNode(8);
 
const p = root.left;
const q = root.left.right;
 
const lca1 = lowestCommonAncestor(root, p, q);
console.log(`LCA of ${p.val} and ${q.val} is ${lca1.val}`);
 
const x = root.right.right;
const y = root.right.right.right;
 
const lca2 = lowestCommonAncestor(root, x, y);
console.log(`LCA of ${x.val} and ${y.val} is ${lca2.val}`);


Output

 LCA of 4 and 3 is 4
 LCA of 7 and 8 is 7




Time Complexity: O(N) , The time complexity of the Morris Traversal approach to find the lowest common ancestor of two nodes in a binary search tree is O(N), where N is the number of nodes in the tree.

Auxiliary Space: O(1) , The space complexity of the Morris Traversal approach is O(1), which is constant extra space.

Related Articles: Lowest Common Ancestor in a Binary Tree, LCA using Parent Pointer, Find LCA in Binary Tree using RMQ

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments