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
相关推荐
codists10 分钟前
2026年8月文章一览
python
外收内放19 分钟前
Python基础语法练习题(31-33)
开发语言·python
2601_9628857227 分钟前
如何用 Python 画 K 线图(蜡烛图)?(mplfinance + 均线 + 成交量)
开发语言·python
tangguofeng1 小时前
基于分治策略的循环赛日程表问题的思路讲解
算法
Y3815326621 小时前
行业动态周报:用新闻 API 追踪一个赛道的声音变化
python·搜索引擎
起个名字费劲死了1 小时前
VisionMaster集成深度学习算法(基础狗)
人工智能·深度学习·算法
lengxuenong1 小时前
枚举例题分析
c++·算法·青少年编程
零域码客2 小时前
零基础Python爬虫入门:从HTTP协议到 requests + BeautifulSoup 实战
爬虫·python·http
“AI国潮设计-小江”2 小时前
【SDXL实战】用AI生成“财神爷蛋糕×英歌舞人物”潮汕国潮甜品IP,附Prompt与批量生成思路
开发语言·人工智能·python·aigc
DD云验证2 小时前
DD云验证,免费网络验证系统
服务器·python·易语言·网络验证·卡密验证