# Concise 48ms C++ solution with description and comment on trees

• The idea is to first fast forward each pointer to the end to find their distances from the end. Then we can fast forward the farther pointer so they're the same distance from the end. Finally we can fast forward both at the same time until they coincide.

This same exact approach can also be used to find the least common ancestor (LCA) of two nodes in a tree where nodes have parent pointers.

``````class Solution {
public:

int countA = 0, countB = 0;

while (currA) {
currA = currA->next, countA++;
}
while (currB) {
currB = currB->next, countB++;
}
int diff = std::abs(countA - countB);
while (diff--) {
}
}
}
};``````

• niubility~~~~

• smart idea, jump the different amount of node, and then move&compare.
Niubility~~~

• What if the following?
A: 1->2->6->7->8
B: 3->4->5->6->7->9

• Really smart and non-tricky solution!
Vote for you

• I think the result from this solution is wrong under your case

• ``````int getnodenum(ListNode *head)
{
int num = 0;
while (p)
{
num++;
p = p->next;
}

return num;
}

{

for (int i = 0; i < n1 - n2; i++)
{
p1 = p1->next;
}

for (int i = 0; i < n2; i++)
{
if (p1 == p2)
return p1;
else
{
p1 = p1->next;
p2 = p2->next;
}
}

return NULL;
}

int numA = getnodenum(p1);
int numB = getnodenum(p2);

if (numA >= numB)
{
return findnode(p1, p2, numA, numB);
}

if (numB > numA)
{
return findnode(p2, p1, numB, numA);
}

}``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.