Lowest Common Ancestor of a Binary Tree III

medium tree two pointers lca

Problem

You are given two nodes p and q of a binary tree. Each node carries a parent pointer in addition to left and right. There is no separate root reference. Return their lowest common ancestor.

Walking from any node through its parents reaches the root, so each node defines a path to the root. The LCA is the first node shared by the two upward paths.

Inputtree = [3,5,1,6,2,0,8], p = 5, q = 1
Output3
Walking up from 5 reaches 3; walking up from 1 reaches 3. Their first shared ancestor is 3.

def lowest_common_ancestor(p, q):
    a, b = p, q
    while a is not b:
        a = a.parent if a else q
        b = b.parent if b else p
    return a
function lowestCommonAncestor(p, q) {
  let a = p, b = q;
  while (a !== b) {
    a = a ? a.parent : q;
    b = b ? b.parent : p;
  }
  return a;
}
class Solution {
    public Node lowestCommonAncestor(Node p, Node q) {
        Node a = p, b = q;
        while (a != b) {
            a = (a != null) ? a.parent : q;
            b = (b != null) ? b.parent : p;
        }
        return a;
    }
}
Node* lowestCommonAncestor(Node* p, Node* q) {
    Node* a = p;
    Node* b = q;
    while (a != b) {
        a = a ? a->parent : q;
        b = b ? b->parent : p;
    }
    return a;
}
Time: O(h) Space: O(1)