Post-order search
Time O(n) Space O(h)find(n): null → null; if n is p or q return n; l = find(left), r = find(right); if both non-null return n; else return the non-null one.
root = [3,5,1,6,2,0,8,null,null,7,4], p = 6, q = 4Step 1/4Searching under 5: its left child 6 is p, so it reports 6.
class Solution {
public int lowestCommonAncestor(TreeNode root, int p, int q) {
return find(root, p, q).val;
}
private TreeNode find(TreeNode n, int p, int q) {
if (n == null || n.val == p || n.val == q) return n;
TreeNode l = find(n.left, p, q), r = find(n.right, p, q);
if (l != null && r != null) return n;
return l != null ? l : r;
}
}Verdict: One pass, no parent pointers.