Leetcode 235. Lowest Common Ancestor of a Binary Search Tree

Problem

Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.

According to the definition of LCA on Wikipedia: "The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself)."

Algorithm

Since it's a BST, compare values to locate the target node. If the current node's value is less than both node values, search the left subtree. If it's greater than both, search the right subtree. Otherwise, the current node is the LCA.

Code

python3 复制代码
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        while root:
            if p.val < root.val and q.val < root.val:
                root = root.left
            elif p.val > root.val and q.val > root.val:
                root = root.right
            else:
                return root
相关推荐
m0_6464299711 分钟前
Python pytest 单元测试基础
python
AI殉道师18 分钟前
合因科技三大临床试验数字化模块:EDC + RTSM(IWRS)+ ePRO,从入组到随访如何协同?
科技·算法·临床试验数字化
DeepVisionary26 分钟前
从1秒多压到0.39秒,Gemini 4 Live靠先应声再干活,把语音延迟降了3倍
python·自动化
Web3&Basketball29 分钟前
Playwright实战:27B网页智能体评测3步
python·大模型·浏览器自动化·playwright·网页智能体·评测口径·molmoweb
zc.z33 分钟前
RAG (一):从底层原理、Naive RAG 到企业级项目开发与面试实战
人工智能·python·rag
Shaoshing1 小时前
LeetCode100 76.最小覆盖字串
java·算法·leetcode
王者鳜錸1 小时前
【中英】-Android离线语音听写-讯飞 AIKit源码实现
开发语言·python·智能手机·安卓·离线中英识别
不知棋者1 小时前
蓝桥杯 2020 省赛 B 组既约分数:从暴力枚举到欧拉函数前缀和
c++·算法·职场和发展·蓝桥杯
电科_银尘2 小时前
【大模型算法与工程 63】视觉语言模型:视觉编码器如何接入LLM
人工智能·算法·语言模型
小蒋学算法2 小时前
算法-三个无重叠子数组的最大和-前缀和+前缀和最值维护
数据结构·算法