Example - nodes in different subtrees
Input
root = TreeNode(3, TreeNode(5), TreeNode(1)), p = root.left (value 5), q = root.right (value 1)
Output
3
The root (3) is the lowest node that has both 5 and 1 as descendants.
Full lesson preview
Given a binary tree and two nodes, find their lowest common ancestor (LCA).
Problem statement
Task
Examples
Input
root = TreeNode(3, TreeNode(5), TreeNode(1)), p = root.left (value 5), q = root.right (value 1)
Output
3
The root (3) is the lowest node that has both 5 and 1 as descendants.
Input format
Output format
Constraints
Samples
Input
root = TreeNode(3, TreeNode(5, TreeNode(6), TreeNode(2, TreeNode(7), TreeNode(4))), TreeNode(1, TreeNode(0), TreeNode(8))); p = node 5; q = node 1
Output
3
Nodes 5 and 1 are in different subtrees; the LCA is the root 3.