v9.1.1
Menu

Lowest Common Ancestor of Binary Tree

mediumFREETrees & BFS/DFSMeta DSA

Given a binary tree (as a level-order array) and two node values p and q, find their lowest common ancestor (LCA).

The LCA is the deepest node that has both p and q as descendants (a node can be a descendant of itself).

Output the value of the LCA.

Example

Input
3,5,1,6,2,0,8,null,null,7,4
5
1
Output
3
Reasoning
  • The binary tree is constructed from the level-order array: 3,5,1,6,2,0,8,null,null,7,4, resulting in the following tree structure: 3 /
    5 1 / \ /
    6 2 0 8 /
    7 4
  • The nodes with values p = 5 and q = 1 are identified in the tree.
  • We find the lowest common ancestor by moving up from p and q until we find a common node, which is the root node 3 in this case.
  • Since 3 is the deepest node that has both 5 and 1 as descendants, its value is the output: 33.

Constraints

  • 2 <= number of nodes <= 10^5
  • All node values are unique
  • p != q
  • Both p and q exist in the tree

Learn this in

More from Meta DSA

solution.py

Test results

Sign in to run your code against the test cases.