← Deloitte bank

Deloitte · Question 67 · Trees

Lowest Common Ancestor of BST

TreesJavacode⏱ O(h)💾 O(1)
Service-based

Problem

For a BST, compare node values: if both less than root go left, both greater go right, else root is the LCA.

Approach

Walk down using BST order until the split point.

Time O(h)Space O(1)

How it works

  1. 1Both targets left means go left; both right means go right.
  2. 2The split node is the LCA.

Sample input / output

Input:
root = [6, 2, 8, 0, 4, 7, 9, null, null, 3, 5], p = 2, q = 8
Output:
6

Constraints

BST property holds; p and q exist.

Solution — read it, then walk it

Time O(h)Space O(1)Loops 4Branches 9Returns 4source · Java
Scroll sideways for wide charts — the view follows the active step.
↻ repeat↻ repeat↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE class TreeNodeDEFINE valTreeNode left, rightTreeNode(int v) { val = v;}DEFINE TreeNodebuildTree(Integer[] values)if (values.length == 0|| values[0] == null)return nullTreeNode root = newTreeNode(values[0])java.util.Queue<TreeNode> q= newjava.util.LinkedList<>()q.offer(root)DEFINE i = 1while (!q.isEmpty() &&i < values.length)TreeNode node = q.poll()if (i < values.length&& values[i] != null){ node.left = ne…i++if (i < values.length&& values[i] != null){ node.right = ne…i++RETURN rootDEFINE StringlevelOrder(TreeNode root)if (root == null)return "[]"StringBuilder sb = newStringBuilder("[")java.util.Queue<TreeNode> q= newjava.util.LinkedList<>()q.offer(root)DEFINE first = truewhile (!q.isEmpty())TreeNode node = q.poll()if (node == null)continueif (!first)sb.append(", ")first = falsesb.append(node.val)q.offer(node.left)q.offer(node.right)RETURNsb.append("]").toString()DEFINE static TreeNodelowestCommonAncestor(TreeNoderoot, TreeNode p, TreeNod…while (root != null)if (p.val < root.val&& q.val < root.val)root = root.leftelse if (p.val >root.val && q.val >root.val) root …ELSERETURN nullDEFINE TreeNodefind(TreeNode root, intval)while (root != null &&root.val != val)root = (val < root.val) ?root.left : root.rightRETURN rootDEFINE static voidmain(String[] args)
  • 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