I went through the algorithm’s for finding the LCA of two nodes in a binary tree (let’s say the values are random – not a binary search tree) and I chose the method where the path to root is stored in an array. That is, an array stores the parent values from one node to the root and the same is done to the second node and finally the arrays are compared to find the first mutual parent.
I got stuck when finding the time complexity of this algorithm. I have a feeling that, it depends on the path length of a node to the root. Is there a generalised equation for the path length of a binary tree? If not, how can I compute the time complexity of this algorithm?
PS-I want to find the time complexity wrt to n=number of nodes/elements
Node findLCA(BT tree, Node N1, Node N2){
Array parentsN1;
Array parentsN2;
while(N1.parent != null){
parentsN1.append(N1.parent)
N1=N1.parent;
}
while(N2.parent != null){
parentsN2.append(N2.parent)
N2=N2.parent;
}
for(i in parentsN1){
for(j in parentsN2){
if (i==j) return i;{
return null;
}
}
}
}