235. Lowest Common Ancestor of a Binary Search Tree
Tags:
Medium
Skills:
Tree
June 24, 2025
04:32 AM
No headings found
Loading content...
Related Posts
Leetcode
No headings found
Related Posts
Leetcode
Problem
Bài toán yêu cầu tìm tổ tiên chung thấp nhất (Lowest common ancestor - LCA) của hai node p và q trong một BST. LCA là node thấp nhất trong cây mà cả p và q đều là hậu duệ (có thể tính cả chính nó)
Approach -
Time and space complexity
Solution
1/**
2 * Definition for a binary tree node.
3 * class TreeNode {
4 * val: number
5 * left: TreeNode | null
6 * right: TreeNode | null
7 * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
8 * this.val = (val===undefined ? 0 : val)
9 * this.left = (left===undefined ? null : left)
10 * this.right = (right===undefined ? null : right)
11 * }
12 * }
13 */
14
15function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null): TreeNode | null {
16 while(root) {
17 if(root.val > p.val && root.val > q.val) {
18 root = root.left;
19 } else if(root.val < p.val && root.val < q.val) {
20 root = root.right
21 } else {
22 return root
23 }
24 }
25 return null;
26};