MentorNode
Start free
Tree BFS & DFS/medium

Lowest Common Ancestor of a Binary Tree

tree-bfs-dfslowest-common-ancestor-of-a-binary-tree

Lowest Common Ancestor of a Binary Tree

Given a binary tree and two target node values p and q, find the Lowest Common Ancestor (LCA) node value.

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).

Example 1

Input: tree = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3

Constraints

  • All Node values are unique.
  • p != q, and both p and q exist in the tree.

Loading workspace editor...
Ready to run
Input:
{
  "tree": [
    3,
    5,
    1,
    6,
    2,
    0,
    8,
    null,
    null,
    7,
    4
  ],
  "p": 5,
  "q": 1
}
Expected Output:
3