← Uber bank

Uber · Question 51 · Trees

Lowest Common Ancestor of a Binary Tree

TreesPythoncode⏱ O(n)💾 O(h)
Product-based

Problem

Given a binary tree and two nodes p and q, find their lowest common ancestor (LCA).

Approach

Use DFS. If root is None, return None. If root is p or q, return root. Recurse both sides; if both return a node, root is the LCA.

Time O(n)Space O(h)

How it works

  1. 1A target found below is bubbled up.
  2. 2Targets split across sides means the root is the LCA.
  3. 3Otherwise propagate whichever side found one.

Sample input / output

Input:
11 5 1
3 5 1 6 2 0 8 x x 7 4
Output:
3

Constraints

2 <= nodes <= 10^5; all values unique; p and q both exist.

Solution — read it, then walk it

Time O(n)Space O(h)Loops 1Branches 7Returns 8source · Python
Scroll sideways for wide charts — the view follows the active step.
yesnoyesnoyesnoyesnoyesno↻ repeatyesnoyesnoSTARTroot, p, qif not root or root ==p or root == qRETURN rootleft =lowestCommonAncestor(root.left,p, q)right =lowestCommonAncestor(root.right,p, q)if left and rightRETURN rootRETURN left or rightCLASS TreeNodeDEFINE __init__(self,val=0, left=None,right=None)self.val = valself.left = leftself.right = rightDEFINE build_tree(values)if not valuesRETURN Noneroot = TreeNode(values[0])queue = [root]i = 1while queue and i <len(values)node = queue.pop(0)if i < len(values) andvalues[i] is not Nonenode.left =TreeNode(values[i])queue.append(node.left)i += 1if i < len(values) andvalues[i] is not Nonenode.right =TreeNode(values[i])queue.append(node.right)i += 1RETURN rootDEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)DEFINE find(root, val)if not rootRETURN Noneif root.val == valRETURN rootl = find(root.left, val)RETURN l if l elsefind(root.right, val)n = int(next(it)); p_val =int(next(it)); q_val =int(next(it))vals = [None if t == 'x'else int(t) for t in[next(it) for _ i…root = build_tree(vals)print(lowestCommonAncestor(root,find(root, p_val),find(root, q_val)).val)
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/46

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