lowestCommonAncestor<T> function

BinaryTreeNode<T>? lowestCommonAncestor<T>(
  1. BinaryTreeNode<T>? root,
  2. T p,
  3. T q
)

Returns the lowest common ancestor node of values p and q in the binary tree rooted at root. Returns null if either p or q is not present in the tree.

Implementation

BinaryTreeNode<T>? lowestCommonAncestor<T>(BinaryTreeNode<T>? root, T p, T q) {
  if (root == null) return null;

  // Check if both p and q exist in the tree before proceeding
  if (!_containsValue(root, p) || !_containsValue(root, q)) {
    return null;
  }

  return _lcaHelper(root, p, q);
}