public static Node getLCA(Node p, Node q){ int pHeight = getHeight (p); int qHeight = getHeight (q); if (pHeight < qHeight) return getLCAHelper (qHeight - pHeight, p, q); else return getLCAHelper (pHeight - qHeight, q, p); }
private static int getHeight(Node node){ int height = 0; while (node != null) { node = node.parent; height++; } return height; }
private static Node getLCAHelper(int d, Node p, Node q){ //d=q-p, q is the deeper one, p is the upper one for (int i = 0; i < d; i++) { q = q.parent; } while (p != null && q != null) { if (p == q) return p; p = p.parent; q = q.parent; } return null; }