Given the root of a Binary Tree with unique values and two node values n1 and n2, find the Lowest Common Ancestor (LCA). LCA is the deepest node that has both n1 and n2 as descendants.
Note: Both node values are always present in the Binary Tree.
Examples:
Input:
Output: 2 Explanation: As shown below, LCA of 4 and 5 is 2.
Input:
Output: 3 Explanation: As shown below, LCA of 7 and 8 is 3.
[Naive Approach] Using Arrays to Store Paths of Nodes from Root - O(n) Time and O(n) Space
The idea is to store the paths of nodes from the root in two separate arrays. Then start traversing from the 0th index and look simultaneously into the values stored in the arrays, the LCA is the last matching element in both the arrays.
Path from root to 7 = 1 -> 3-> 7 Path from root to 8 = 1 -> 3 -> 6 -> 8
We start checking from 0th index. As both of the values match, we move to the next index.
Now check for values at 1st index, they are also matching, so we move to the 2nd index.
Now, we check for 3rd index, there's a mismatch so we consider the previous value.
Therefore, the LCA of (7, 8) is 3.
C++
#include<iostream>#include<vector>usingnamespacestd;// Node StructureclassNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Function to find path from root to given node.boolfindPath(Node*root,vector<Node*>&path,intn){if(root==nullptr)returnfalse;// Store current node value in the path.path.push_back(root);if(root->data==n||findPath(root->left,path,n)||findPath(root->right,path,n))returntrue;// else remove root from path and return falsepath.pop_back();returnfalse;}Node*lca(Node*root,intn1,intn2){vector<Node*>path1,path2;// Find paths from root to n1// and root to n2.if(!findPath(root,path1,n1)||!findPath(root,path2,n2))returnnullptr;// Compare the paths to get the first// different valueinti;for(i=0;i<path1.size()&&i<path2.size();i++){if(path1[i]!=path2[i])returnpath1[i-1];}returnpath1[i-1];}intmain(){// construct the binary tree// 1// / \ // 2 3// / \ / \ // 4 5 6 7 // /// 8Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->left=newNode(6);root->right->right=newNode(7);root->right->left->left=newNode(8);Node*ans=lca(root,7,8);cout<<ans->data;return0;}
C
#include<stdio.h>#include<stdlib.h>#include<stdbool.h>// maximum number of nodes in path#define MAX 1000 // Node StructurestructNode{intdata;structNode*left;structNode*right;};// Function to create a new nodestructNode*createNode(intx){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=x;node->left=NULL;node->right=NULL;returnnode;}// Function to find path from root to given nodeboolfindPath(structNode*root,structNode*path[],int*pathLen,intn){if(root==NULL)returnfalse;// Store current node in the pathpath[(*pathLen)++]=root;if(root->data==n)returntrue;if(findPath(root->left,path,pathLen,n)||findPath(root->right,path,pathLen,n))returntrue;// else remove root from path and return false(*pathLen)--;returnfalse;}// Function to find LCAstructNode*lca(structNode*root,intn1,intn2){structNode*path1[MAX],*path2[MAX];intlen1=0,len2=0;// Find paths from root to n1 and root to n2if(!findPath(root,path1,&len1,n1)||!findPath(root,path2,&len2,n2))returnNULL;// Compare the paths to get the first different valueinti;for(i=0;i<len1&&i<len2;i++){if(path1[i]!=path2[i])returnpath1[i-1];}returnpath1[i-1];}intmain(){// Construct the binary tree// 1// / \ // 2 3// / \ / \ // 4 5 6 7 // /// 8structNode*root=createNode(1);root->left=createNode(2);root->right=createNode(3);root->left->left=createNode(4);root->left->right=createNode(5);root->right->left=createNode(6);root->right->right=createNode(7);root->right->left->left=createNode(8);structNode*ans=lca(root,7,8);printf("%d\n",ans->data);return0;}
Java
importjava.util.ArrayList;importjava.util.List;// Node StructureclassNode{intdata;Nodeleft,right;Node(intvalue){data=value;left=right=null;}}classGfG{staticNodelca(Noderoot,intn1,intn2){List<Node>path1=newArrayList<>();List<Node>path2=newArrayList<>();// Find paths from root to n1// and root to n2.if(!findPath(root,path1,n1)||!findPath(root,path2,n2))returnnull;// Compare the paths to get the first// different valueinti;for(i=0;i<path1.size()&&i<path2.size();i++){if(path1.get(i)!=path2.get(i))returnpath1.get(i-1);}returnpath1.get(i-1);}// Finds the path from root to given nodestaticbooleanfindPath(Noderoot,List<Node>path,intn){if(root==null){returnfalse;}// Store current nodepath.add(root);if(root.data==n||findPath(root.left,path,n)||findPath(root.right,path,n)){returntrue;}// remove root from path and return falsepath.remove(path.size()-1);returnfalse;}publicstaticvoidmain(String[]args){// construct the binary tree// 1// / \// 2 3// / \ / \// 4 5 6 7 // /// 8Noderoot=newNode(1);root=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);root.right.left.left=newNode(8);Nodeans=lca(root,7,8);System.out.println(ans.data);}}
Python
# Node StructureclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=None# function to find path from root to nodedeffindPath(root,path,k):ifrootisNone:returnFalse# Store current node in pathpath.append(root)if(root.data==korfindPath(root.left,path,k)orfindPath(root.right,path,k)):returnTrue# else remove root from path and return falsepath.pop()returnFalsedeflca(root,n1,n2):path1=[]path2=[]# Find paths from root to n1# and root to n2.if(notfindPath(root,path1,n1)ornotfindPath(root,path2,n2)):returnNone# Compare the paths to get the first different valuei=0while(i<len(path1)andi<len(path2)):ifpath1[i]!=path2[i]:breaki+=1returnpath1[i-1]if__name__=='__main__':# construct the binary tree# 1# / \# 2 3# / \ / \# 4 5 6 7# /# 8root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)root.right.left=Node(6)root.right.right=Node(7)root.right.left.left=Node(8)ans=lca(root,7,8)print(ans.data)
C#
usingSystem;usingSystem.Collections.Generic;// Node StructureclassNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Function to find path from root to given node.// returns true if node with value 'k' lies in the subtree of 'root'staticboolfindPath(Noderoot,List<Node>path,intk){if(root==null)returnfalse;// Store current node value in the path.path.Add(root);if(root.data==k||findPath(root.left,path,k)||findPath(root.right,path,k))returntrue;// else remove root from path and return falsepath.RemoveAt(path.Count-1);returnfalse;}staticNodelca(Noderoot,intn1,intn2){List<Node>path1=newList<Node>();List<Node>path2=newList<Node>();// Find paths from root to n1// and root to n2.if(!findPath(root,path1,n1)||!findPath(root,path2,n2))returnnull;// Compare the paths to get the first// different valueinti;for(i=0;i<path1.Count&&i<path2.Count;i++){if(path1[i]!=path2[i])returnpath1[i-1];}returnpath1[i-1];}staticvoidMain(string[]args){// construct the binary tree// 1// / \// 2 3// / \ / \// 4 5 6 7 // /// 8Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);root.right.left.left=newNode(8);Nodeans=lca(root,7,8);Console.WriteLine(ans.data);}}
JavaScript
// Node StructureclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Function to find path from root to given node.functionfindPath(root,path,k){if(root===null)returnfalse;// Store current node value in the path.path.push(root);if(root.data===k||findPath(root.left,path,k)||findPath(root.right,path,k))returntrue;// else remove root from path and return falsepath.pop();returnfalse;}functionlca(root,n1,n2){letpath1=[];letpath2=[];// Find paths from root to n1// and root to n2.if(!findPath(root,path1,n1)||!findPath(root,path2,n2))returnnull;// Compare the paths to get the first// different valueleti;for(i=0;i<path1.length&&i<path2.length;i++){if(path1[i]!==path2[i])returnpath1[i-1];}returnpath1[i-1];}// Driver code// construct the binary tree// 1// / \// 2 3// / \ / \// 4 5 6 7 // /// 8letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);root.right.left.left=newNode(8);letans=lca(root,7,8);console.log(ans.data);
Output
3
[Expected Approach] Using Single Traversal
The idea is to traverse the tree starting from the root. If any of the given keys (n1 and n2) matches with the root, then the root is LCA (assuming that both keys are present). If the root doesn't match with any of the keys, we go for the left and right subtree. The node which has one key present in its left subtree and the other key present in the right subtree is the LCA, else if, both keys lie in the left subtree, then the left subtree has LCA, else the LCA lies in the right subtree.
C++
#include<iostream>usingnamespacestd;// Node StructureclassNode{public:Node*left,*right;intdata;Node(intk){data=k;left=nullptr;right=nullptr;}};Node*lca(Node*root,intn1,intn2){if(!root)returnnullptr;// If either key matches with root data, return rootif(root->data==n1||root->data==n2)returnroot;Node*leftLca=lca(root->left,n1,n2);Node*rightLca=lca(root->right,n1,n2);// If both of the above calls return Non-NULL, then one// data is present in one subtree and the other is present// in the other, so this node is the LCAif(leftLca&&rightLca)returnroot;// Otherwise check if left subtree or // right subtree is LCAreturnleftLca?leftLca:rightLca;}intmain(){// construct the binary tree// 1// / \ // 2 3// / \ / \ // 4 5 6 7 // /// 8Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->left=newNode(6);root->right->right=newNode(7);root->right->left->left=newNode(8);Node*ans=lca(root,7,8);cout<<ans->data;return0;}
C
#include<stdio.h>#include<stdlib.h>// Node StructurestructNode{structNode*left,*right;intkey;};structNode*lca(structNode*root,intn1,intn2){if(root==NULL)returnNULL;// If either key matches with root data, return rootif(root->key==n1||root->key==n2)returnroot;structNode*leftLca=lca(root->left,n1,n2);structNode*rightLca=lca(root->right,n1,n2);// If both of the above calls return Non-NULL, then one// key is present in once subtree and other is present// in other, so this node is the LCAif(leftLca&&rightLca)returnroot;// Otherwise check if left subtree or // right subtree is LCAreturn(leftLca!=NULL)?leftLca:rightLca;}structNode*createnode(intkey){structNode*newnode=(structNode*)malloc(sizeof(structNode));newnode->key=key;newnode->left=newnode->right=NULL;returnnewnode;}intmain(){// construct the binary tree// 1// / \ // 2 3// / \ / \ // 4 5 6 7 // /// 8structNode*root=createnode(1);root->left=createnode(2);root->right=createnode(3);root->left->left=createnode(4);root->left->right=createnode(5);root->right->left=createnode(6);root->right->right=createnode(7);root->right->left->left=createnode(8);structNode*ans=lca(root,7,8);printf("%d",ans->key);return0;}
Java
// Node StructureclassNode{Nodeleft,right;intdata;Node(intk){data=k;left=null;right=null;}}classGFG{staticNodelca(Noderoot,intn1,intn2){if(root==null)returnnull;// If either key matches with root data, return rootif(root.data==n1||root.data==n2)returnroot;NodeleftLca=lca(root.left,n1,n2);NoderightLca=lca(root.right,n1,n2);// If both of the above calls return Non-NULL, then one// node is present in one subtree and the other is present// in the other, so this node is the LCAif(leftLca!=null&&rightLca!=null)returnroot;// Otherwise check if left subtree or // right subtree is LCAreturn(leftLca!=null)?leftLca:rightLca;}publicstaticvoidmain(String[]args){// construct the binary tree// 1// / \// 2 3// / \ / \// 4 5 6 7 // /// 8Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);root.right.left.left=newNode(8);Nodeans=lca(root,7,8);System.out.println(ans.data);}}
Python
# Node StructureclassNode:def__init__(self,k):self.data=kself.left=Noneself.right=Nonedeflca(root,n1,n2):ifnotroot:returnNone# If either key matches with root data, return rootifroot.data==n1orroot.data==n2:returnrootleftLca=lca(root.left,n1,n2)rightLca=lca(root.right,n1,n2)# If both of the above calls return Non-NULL, then one# data is present in one subtree and the other is present# in the other, so this node is the LCAifleftLcaandrightLca:returnroot# Otherwise check if left subtree or # right subtree is LCAreturnleftLcaifleftLcaelserightLcaif__name__=="__main__":# construct the binary tree# 1# / \# 2 3# / \ / \# 4 5 6 7 # /# 8root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)root.right.left=Node(6)root.right.right=Node(7)root.right.left.left=Node(8)ans=lca(root,7,8)print(ans.data)
C#
usingSystem;// Node StructureclassNode{publicNodeleft,right;publicintdata;publicNode(intk){data=k;left=null;right=null;}}classGFG{staticNodelca(Noderoot,intn1,intn2){if(root==null)returnnull;// If either key matches with root data, return rootif(root.data==n1||root.data==n2)returnroot;NodeleftLca=lca(root.left,n1,n2);NoderightLca=lca(root.right,n1,n2);// If both of the above calls return Non-NULL, then one// data is present in one subtree and the other is present// in the other, so this node is the LCAif(leftLca!=null&&rightLca!=null)returnroot;// Otherwise check if left subtree or // right subtree is LCAreturnleftLca!=null?leftLca:rightLca;}staticvoidMain(){// Construct the binary tree// 1// / \// 2 3// / \ / \// 4 5 6 7 // /// 8Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);root.right.left.left=newNode(8);Nodeans=lca(root,7,8);Console.WriteLine(ans.data);}}
JavaScript
// Node StructureclassNode{constructor(k){this.left=null;this.right=null;this.data=k;}}functionlca(root,n1,n2){if(root===null)returnnull;// If either key matches with root data, return rootif(root.data===n1||root.data===n2)returnroot;letleftLca=lca(root.left,n1,n2);letrightLca=lca(root.right,n1,n2);// If both of the above calls return Non-NULL, then one// data is present in one subtree and the other is present// in the other, so this node is the LCAif(leftLca&&rightLca)returnroot;// Otherwise check if left subtree or // right subtree is LCAreturnleftLca?leftLca:rightLca;}// Construct the binary tree// 1// / \// 2 3// / \ / \// 4 5 6 7// /// 8letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);root.right.left.left=newNode(8);letans=lca(root,7,8);console.log(ans.data);
Output
3
Time Complexity: O(n) Auxiliary Space: O(h), where h is the height of the tree.