Lowest Common Ancestor in a Binary Tree | Set 2 (Using Parent Pointer)
Given values of two nodes in a Binary Tree, find the Lowest Common Ancestor (LCA). It may be assumed that both nodes exist in the tree.

For example, consider the Binary Tree in diagram, LCA of 10 and 14 is 12 and LCA of 8 and 14 is 8.
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). Source : Wikipedia.
We have discussed different approaches to find LCA in set 1. Finding LCA becomes easy when parent pointer is given as we can easily find all ancestors of a node using parent pointer.
Below are steps to find LCA.
- Create an empty hash table.
- Insert n1 and all of its ancestors in hash table.
- Check if n2 or any of its ancestors exist in hash table, if yes return the first existing ancestor.
Below is the implementation of above steps.
C
// C++ program to find lowest common ancestor using parent pointer#include <bits/stdc++.h>usingnamespacestd;// A Tree NodestructNode{Node *left, *right, *parent;intkey;};// A utility function to create a new BST nodeNode *newNode(intitem){Node *temp =newNode;temp->key = item;temp->parent = temp->left = temp->right = NULL;returntemp;}/* A utility function to insert a new node withgiven key in Binary Search Tree */Node *insert(Node *node,intkey){/* If the tree is empty, return a new node */if(node == NULL)returnnewNode(key);/* Otherwise, recur down the tree */if(key < node->key){node->left = insert(node->left, key);node->left->parent = node;}elseif(key > node->key){node->right = insert(node->right, key);node->right->parent = node;}/* return the (unchanged) node pointer */returnnode;}// To find LCA of nodes n1 and n2 in Binary TreeNode *LCA(Node *n1, Node *n2){// Creata a map to store ancestors of n1map <Node *,bool> ancestors;// Insert n1 and all its ancestors in mapwhile(n1 != NULL){ancestors[n1] =true;n1 = n1->parent;}// Check if n2 or any of its ancestors is in// map.while(n2 != NULL){if(ancestors.find(n2) != ancestors.end())returnn2;n2 = n2->parent;}returnNULL;}// Driver method to test above functionsintmain(void){Node * root = NULL;root = insert(root, 20);root = insert(root, 8);root = insert(root, 22);root = insert(root, 4);root = insert(root, 12);root = insert(root, 10);root = insert(root, 14);Node *n1 = root->left->right->left;Node *n2 = root->left;Node *lca = LCA(n1, n2);printf("LCA of %d and %d is %d \n", n1->key, n2->key, lca->key);return0;}Java
importjava.util.HashMap;importjava.util.Map;// Java program to find lowest common ancestor using parent pointer// A tree nodeclassNode{intkey;Node left, right, parent;Node(intkey){this.key = key;left = right = parent =null;}}classBinaryTree{Node root, n1, n2, lca;/* A utility function to insert a new node withgiven key in Binary Search Tree */Node insert(Node node,intkey){/* If the tree is empty, return a new node */if(node ==null)returnnewNode(key);/* Otherwise, recur down the tree */if(key < node.key){node.left = insert(node.left, key);node.left.parent = node;}elseif(key > node.key){node.right = insert(node.right, key);node.right.parent = node;}/* return the (unchanged) node pointer */returnnode;}// To find LCA of nodes n1 and n2 in Binary TreeNode LCA(Node n1, Node n2){// Creata a map to store ancestors of n1Map<Node, Boolean> ancestors =newHashMap<Node, Boolean>();// Insert n1 and all its ancestors in mapwhile(n1 !=null){ancestors.put(n1, Boolean.TRUE);n1 = n1.parent;}// Check if n2 or any of its ancestors is in// map.while(n2 !=null){if(ancestors.containsKey(n2) != ancestors.isEmpty())returnn2;n2 = n2.parent;}returnnull;}// Driver method to test above functionspublicstaticvoidmain(String[] args){BinaryTree tree =newBinaryTree();tree.root = tree.insert(tree.root,20);tree.root = tree.insert(tree.root,8);tree.root = tree.insert(tree.root,22);tree.root = tree.insert(tree.root,4);tree.root = tree.insert(tree.root,12);tree.root = tree.insert(tree.root,10);tree.root = tree.insert(tree.root,14);tree.n1 = tree.root.left.right.left;tree.n2 = tree.root.left;tree.lca = tree.LCA(tree.n1, tree.n2);System.out.println("LCA of "+ tree.n1.key +" and "+ tree.n2.key+" is "+ tree.lca.key);}}// This code has been contributed by Mayank Jaiswal(mayank_24)C#
// C# program to find lowest common ancestor using parent pointer// A tree nodeusingSystem;usingSystem.Collections;usingSystem.Collections.Generic;publicclassNode{publicintkey;publicNode left, right, parent;publicNode(intkey){this.key = key;left = right = parent =null;}}classBinaryTree{Node root, n1, n2, lca;/* A utility function to insert a new node withgiven key in Binary Search Tree */Node insert(Node node,intkey){/* If the tree is empty, return a new node */if(node ==null)returnnewNode(key);/* Otherwise, recur down the tree */if(key < node.key){node.left = insert(node.left, key);node.left.parent = node;}elseif(key > node.key){node.right = insert(node.right, key);node.right.parent = node;}/* return the (unchanged) node pointer */returnnode;}// To find LCA of nodes n1 and n2 in Binary TreeNode LCA(Node n1, Node n2){// Creata a map to store ancestors of n1Dictionary<Node, Boolean> ancestors =newDictionary<Node, Boolean>();// Insert n1 and all its ancestors in mapwhile(n1 !=null){ancestors.Add(n1,true);n1 = n1.parent;}// Check if n2 or any of its ancestors is in// map.while(n2 !=null){if(ancestors.ContainsKey(n2))returnn2;n2 = n2.parent;}returnnull;}// Driver codepublicstaticvoidMain(String []args){BinaryTree tree =newBinaryTree();tree.root = tree.insert(tree.root, 20);tree.root = tree.insert(tree.root, 8);tree.root = tree.insert(tree.root, 22);tree.root = tree.insert(tree.root, 4);tree.root = tree.insert(tree.root, 12);tree.root = tree.insert(tree.root, 10);tree.root = tree.insert(tree.root, 14);tree.n1 = tree.root.left.right.left;tree.n2 = tree.root.left;tree.lca = tree.LCA(tree.n1, tree.n2);Console.WriteLine("LCA of "+ tree.n1.key +" and "+ tree.n2.key+" is "+ tree.lca.key);}}// This code is contributed by Arnab Kundu
Output:LCA of 10 and 8 is 8
Note : The above implementation uses insert of Binary Search Tree to create a Binary Tree, but the function LCA is for any Binary Tree (not necessarily a Binary Search Tree).
Time Complexity : O(h) where h is height of Binary Tree if we use hash table to implement the solution (Note that the above solution uses map which takes O(Log h) time to insert and find). So the time complexity of above implementation is O(h Log h).Auxiliary Space : O(h)
A O(h) time and O(1) Extra Space Solution:
The above solution requires extra space because we need to use a hash table to store visited ancestors. We can solve the problem in O(1) extra space using following fact : If both nodes are at same level and if we traverse up using parent pointers of both nodes, the first common node in the path to root is lca.
The idea is to find depths of given nodes and move up the deeper node pointer by the difference between depths. Once both nodes reach same level, traverse them up and return the first common node.Thanks to Mysterious Mind for suggesting this approach.
C++
// C++ program to find lowest common ancestor using parent pointer#include <bits/stdc++.h>usingnamespacestd;// A Tree NodestructNode{Node *left, *right, *parent;intkey;};// A utility function to create a new BST nodeNode *newNode(intitem){Node *temp =newNode;temp->key = item;temp->parent = temp->left = temp->right = NULL;returntemp;}/* A utility function to insert a new node withgiven key in Binary Search Tree */Node *insert(Node *node,intkey){/* If the tree is empty, return a new node */if(node == NULL)returnnewNode(key);/* Otherwise, recur down the tree */if(key < node->key){node->left = insert(node->left, key);node->left->parent = node;}elseif(key > node->key){node->right = insert(node->right, key);node->right->parent = node;}/* return the (unchanged) node pointer */returnnode;}// A utility function to find depth of a node// (distance of it from root)intdepth(Node *node){intd = -1;while(node){++d;node = node->parent;}returnd;}// To find LCA of nodes n1 and n2 in Binary TreeNode *LCA(Node *n1, Node *n2){// Find depths of two nodes and differencesintd1 = depth(n1), d2 = depth(n2);intdiff = d1 - d2;// If n2 is deeper, swap n1 and n2if(diff < 0){Node * temp = n1;n1 = n2;n2 = temp;diff = -diff;}// Move n1 up until it reaches the same level as n2while(diff--)n1 = n1->parent;// Now n1 and n2 are at same levelswhile(n1 && n2){if(n1 == n2)returnn1;n1 = n1->parent;n2 = n2->parent;}returnNULL;}// Driver method to test above functionsintmain(void){Node * root = NULL;root = insert(root, 20);root = insert(root, 8);root = insert(root, 22);root = insert(root, 4);root = insert(root, 12);root = insert(root, 10);root = insert(root, 14);Node *n1 = root->left->right->left;Node *n2 = root->right;Node *lca = LCA(n1, n2);printf("LCA of %d and %d is %d \n", n1->key, n2->key, lca->key);return0;}Java
importjava.util.HashMap;importjava.util.Map;// Java program to find lowest common ancestor using parent pointer// A tree nodeclassNode{intkey;Node left, right, parent;Node(intkey){this.key = key;left = right = parent =null;}}classBinaryTree{Node root, n1, n2, lca;/* A utility function to insert a new node withgiven key in Binary Search Tree */Node insert(Node node,intkey){/* If the tree is empty, return a new node */if(node ==null)returnnewNode(key);/* Otherwise, recur down the tree */if(key < node.key){node.left = insert(node.left, key);node.left.parent = node;}elseif(key > node.key){node.right = insert(node.right, key);node.right.parent = node;}/* return the (unchanged) node pointer */returnnode;}// A utility function to find depth of a node// (distance of it from root)intdepth(Node node){intd = -1;while(node !=null){++d;node = node.parent;}returnd;}// To find LCA of nodes n1 and n2 in Binary TreeNode LCA(Node n1, Node n2){// Find depths of two nodes and differencesintd1 = depth(n1), d2 = depth(n2);intdiff = d1 - d2;// If n2 is deeper, swap n1 and n2if(diff <0){Node temp = n1;n1 = n2;n2 = temp;diff = -diff;}// Move n1 up until it reaches the same level as n2while(diff-- !=0)n1 = n1.parent;// Now n1 and n2 are at same levelswhile(n1 !=null&& n2 !=null){if(n1 == n2)returnn1;n1 = n1.parent;n2 = n2.parent;}returnnull;}// Driver method to test above functionspublicstaticvoidmain(String[] args){BinaryTree tree =newBinaryTree();tree.root = tree.insert(tree.root,20);tree.root = tree.insert(tree.root,8);tree.root = tree.insert(tree.root,22);tree.root = tree.insert(tree.root,4);tree.root = tree.insert(tree.root,12);tree.root = tree.insert(tree.root,10);tree.root = tree.insert(tree.root,14);tree.n1 = tree.root.left.right.left;tree.n2 = tree.root.right;tree.lca = tree.LCA(tree.n1, tree.n2);System.out.println("LCA of "+ tree.n1.key +" and "+ tree.n2.key+" is "+ tree.lca.key);}}// This code has been contributed by Mayank Jaiswal(mayank_24)C#
// C# program to find lowest common// ancestor using parent pointerusingSystem;// A tree nodepublicclassNode{publicintkey;publicNode left, right, parent;publicNode(intkey){this.key = key;left = right = parent =null;}}classGFG{publicNode root, n1, n2, lca;/* A utility function to insert a newnode with given key in Binary Search Tree */publicvirtualNode insert(Node node,intkey){/* If the tree is empty, returna new node */if(node ==null){returnnewNode(key);}/* Otherwise, recur down the tree */if(key < node.key){node.left = insert(node.left, key);node.left.parent = node;}elseif(key > node.key){node.right = insert(node.right, key);node.right.parent = node;}/* return the (unchanged) node pointer */returnnode;}// A utility function to find depth of a// node (distance of it from root)publicvirtualintdepth(Node node){intd = -1;while(node !=null){++d;node = node.parent;}returnd;}// To find LCA of nodes n1 and n2// in Binary TreepublicvirtualNode LCA(Node n1, Node n2){// Find depths of two nodes// and differencesintd1 = depth(n1), d2 = depth(n2);intdiff = d1 - d2;// If n2 is deeper, swap n1 and n2if(diff < 0){Node temp = n1;n1 = n2;n2 = temp;diff = -diff;}// Move n1 up until it reaches// the same level as n2while(diff-- != 0){n1 = n1.parent;}// Now n1 and n2 are at same levelswhile(n1 !=null&& n2 !=null){if(n1 == n2){returnn1;}n1 = n1.parent;n2 = n2.parent;}returnnull;}// Driver CodepublicstaticvoidMain(string[] args){GFG tree =newGFG();tree.root = tree.insert(tree.root, 20);tree.root = tree.insert(tree.root, 8);tree.root = tree.insert(tree.root, 22);tree.root = tree.insert(tree.root, 4);tree.root = tree.insert(tree.root, 12);tree.root = tree.insert(tree.root, 10);tree.root = tree.insert(tree.root, 14);tree.n1 = tree.root.left.right.left;tree.n2 = tree.root.right;tree.lca = tree.LCA(tree.n1, tree.n2);Console.WriteLine("LCA of "+ tree.n1.key +" and "+ tree.n2.key +" is "+ tree.lca.key);}}// This code is contributed by Shrikant13
Output :LCA of 10 and 22 is 20
You may like to see below articles as well :
Lowest Common Ancestor in a Binary Tree | Set 1
Lowest Common Ancestor in a Binary Search Tree.
Find LCA in Binary Tree using RMQ
This article is contributed by Dheeraj Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.



