First Common Ancestor
struct Node {
int val;
Node *left;
Node *right;
Node *parent;
Node(int x, Node *p) :
val(x), left(NULL), right(NULL), parent(p) {}
};Node* firstCommonAncestor(Node *one, Node* two) {
if (!one || !two) return nullptr;
int distance = depth(one) - depth(two);
// if (-), then two is larger, so increment it first, and vise-versa
if (distance < 0) {
for (int i = 0; i < abs(distance); i++) {
two = two->parent;
}
// now increment at the same time
while (one != two) {
one = one->parent;
two = two->parent;
}
}
else {
for (int i = 0; i < abs(distance); i++) {
one = one->parent;
}
// now increment at the same time
while (one != two) {
one = one->parent;
two = two->parent;
}
}
return one; // or two
}
int depth(Node *node) {
int depth = 0;
while (node->parent) {
depth++;
node = node->parent;
}
return depth;
}Last updated