You are given BST and two nodes. Find their lowest common ancestor.
Approach
Walk down using the BST order until the split point.
Time O(h)Space O(h)
How it works
1Both targets left means go left; both right means go right.
2The split node is the LCA.
Sample input / output
Input:
10 2 4
6 2 8 0 4 7 9 x x 3 5
Output:
2
Constraints
2 <= nodes <= 10^5; unique values; p and q exist.
Solution — read it, then walk it
Time O(h)Space O(h)Loops 2Branches 7Returns 7source · Python
Scroll sideways for wide charts — the view follows the active step.
start / end
statement
condition
loop
returns
definition
1/45
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books →Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses →Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits →