Problem
You get the root root of a binary search tree (BST). In a BST, each node has at most two children: a left child and a right child.
The subtree of a node is the node itself and all the nodes below it. The left subtree of a node is the subtree of its left child. The right subtree is the subtree of its right child.
In a BST, all values in the left subtree of a node are smaller than the node value. All values in the right subtree are larger.
You also get two different nodes p and q of the tree. Return their lowest common ancestor. This is the node farthest from the root that has both p and q in its subtree. So the answer can be p or q itself.
The examples show each tree as a list in level order. This list gives the nodes row by row, from left to right. The value null marks a missing child. The examples show p, q and the answer by their values.
Example 1
- Input:
- root = [20,10,30,5,15,25,35], p = 5, q = 15
- Output:
- 10
- Explanation:
- The nodes
5and15are the two children of node10.
Example 2
- Input:
- root = [20,10,30,5,15,25,35], p = 30, q = 35
- Output:
- 30
- Explanation:
- Node
35is below node30, and node30is in its own subtree. So the answer isp.
Example 3
- Input:
- root = [40,20,60,10,30,50,70,null,null,25,35], p = 25, q = 10
- Output:
- 20
Constraints
- 2 <= number of nodes <= 10^5
- -10^9 <= Node.val <= 10^9
- All node values are different.
- p != q
- p and q are nodes of the tree.
SysRound wrote this statement. A reference solution checks every example.
Related questions
Continue with questions that share topics or the same question type.
- Lowest Common Ancestor of a Binary Tree
Coding · Binary Lifting · Binary Tree · Depth-First Search
- Lowest Common Ancestor of a Binary Tree II
Coding
- Lowest Common Ancestor of a Binary Tree III
Coding · Binary Lifting · Binary Tree · Hash Table
- Lowest Common Ancestor of a Binary Tree IV
Coding
Sources · 1 reference
These records explain where the question appears. A company tag or candidate report does not guarantee a future interview question.
Hello Interview · 1 record
LinkedIn
Leetcode 235. Lowest Common Ancestor of a Binary Search Tree
Reported Jan 7, 2026 · 6 source reports
JUNIOR, MID_LEVEL, SENIOR
Source snapshot: Nov 12, 2026
View source