<AI/>
enru
Все статьи

Lowest common ancestor of a binary tree

LeetCode 236: Find the lowest common ancestor of two nodes in a binary tree with a recursive DFS.

Сложность
Средняя
Опубликовано
Темы
#tree#binary tree
Открыть на LeetCode

Статья пока доступна только на английском.

Problem Description

You are given a binary tree. Find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: "The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself)."

Constraints

  • The number of nodes in the tree is in the range from 2 to 105.
  • Node values are in the range from -109 to 109.
  • All node values are unique.
  • p != q.
  • p and q always exist in the tree.

Examples

3 LCA 5 p 1 q 6 2 0 8 7 4

Input: the tree above, p = 5, q = 1.

Answer: 3

Explanation: The LCA of nodes 5 and 1 is 3.

Solution

The solution to this problem is fairly intuitive. We traverse the tree depth-first. As soon as we meet either p or q, we return a boolean flag. The flag tells us whether we've found the target nodes along some path. The lowest common ancestor is then the node for which both subtree recursions return true. It can also be a node that is itself one of p or q and for which one of the subtree recursions returns true.

We'll use a recursive approach with a closure to store the lca variable.

typescript
export type TreeNode = {
  val: number;
  left?: TreeNode;
  right?: TreeNode;
};
 
export const lowestCommonAncestor = (root?: TreeNode, p?: TreeNode, q?: TreeNode): TreeNode | null => {
  let lca: TreeNode | null = null;
 
  const findNode = (node?: TreeNode): boolean => {
    if (!node || !p || !q) {
      return false;
    }
 
    const left = findNode(node.left);
    const right = findNode(node.right);
 
    if (left && right) {
      lca = node;
      return true;
    }
 
    if (node.val == p.val || node.val == q.val) {
      if (left || right) {
        lca = node;
      }
      return true;
    }
 
    return left || right;
  };
 
  findNode(root);
 
  return lca;
};

Complexity Analysis

Time Complexity

O(n), since in the worst case we need to visit all n nodes of the tree.

Space Complexity

O(n), since the maximum space used by the recursion stack is n.