As reported: Amazon SDE new grad (L4) final round (2025), interview 1 of three back-to-back, second question: the lowest common ancestor of two nodes in a tree where each node has a parent pointer.
You are given two nodes p and q of a binary tree; each node has val, left, right and parent. You are not given the root. Return their lowest common ancestor — the lowest node that has both p and q as descendants (a node is a descendant of itself).
This is LeetCode 1650 — Lowest Common Ancestor of a Binary Tree III.
Example 1
tree = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Example 2
tree = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Example 3
tree = [1,2], p = 1, q = 2
Output: 1
Constraints: 2 ≤ nodes ≤ 10⁵; values are unique; p ≠ q; both exist in the tree.
Code runner format: one JSON value per line: the tree in LeetCode's level-order format, then the values of p and q. The harness builds the nodes with parent links, calls lowestCommonAncestor(p, q) and prints the returned node's value.