Lowest Common Ancestor of a Binary Tree II Problem
Description
LeetCode Problem 1644.
Given the root of a binary tree, return the lowest common ancestor (LCA) of two given nodes, p and q. If either node p or q does not exist in the tree, return null. All values of the nodes in the tree are unique.
According to the definition of LCA on Wikipedia: "The lowest common ancestor of two nodes p and q in a binary tree T is the lowest node that has both p and q as descendants (where we allow a node to be a descendant of itself)". A descendant of a node x is a node y that is on the path from node x to some leaf node.
Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.
Example 2:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5. A node can be a descendant of itself according to the definition of LCA.
Example 3:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 10
Output: null
Explanation: Node 10 does not exist in the tree, so return null.
Constraints:
- The number of nodes in the tree is in the range
[1, 10^4]. -10^9 <= Node.val <= 10^9- All
Node.valare unique. p != q
Follow up: Can you find the LCA traversing the tree, without checking nodes existence?
Solution
Approach: Postorder DFS That Counts What It Found
In the usual LCA problem, both nodes are guaranteed to be in the tree, so returning the first of p or q that we meet is enough. Here one of them might be missing. Then that shortcut would be wrong: in Example 3 it would return node 5, but the answer is null. So we must search the whole tree and only report a node when we have really seen both.
Let contains(node) return whether the subtree at node holds p or q. It looks at three things:
left: the left subtree holds one of them;right: the right subtree holds one of them;here:nodeitself isporq.
If at least two of these are true, this subtree holds both nodes, and node is the lowest such node, because it is the first node, going up from the bottom, where the two are joined. Store it as the answer. Return left or right or here to the parent.
Since the values are unique and p != q, at most one node ever has two of the three true, so the answer is set at most once. If p or q is not in the tree, it is never set and stays null.
Complexity: O(n) time, visiting every node once. O(h) extra space for the recursion, where h is the height of the tree.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
ans = None
def contains(node):
"""Whether the subtree at node holds p or q; sets ans at the node that holds both."""
nonlocal ans
if node is None:
return False
left = contains(node.left)
right = contains(node.right)
here = node is p or node is q
if left + right + here >= 2:
ans = node
return left or right or here
contains(root)
return ans