LCA of two tree nodes
Given two nodes in a binary tree. Find their lowest common ancestor.
Ex:
LCA(1, 2) = 9
Solution: Recursive traversal
Base Case:
current node == null; return null
current node == node1 || node 2; return current
Recursive Rule:
Initialize two new nodes, left and right
if both not null, found, return
if one found, return it up
if both null, return null
Implementation:
Time complexity: Every node traveled O(N)
Space complexity: No additional struct used O(1) Call stack worst case O(h)
Last updated
Was this helpful?