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
相关推荐
好家伙VCC几秒前
Rust+Bioinfo:80ms极速SNP注释引擎
java·开发语言·算法·rust
啦哈拉哈1 分钟前
【Python】知识点零碎学习7
python·学习·算法
宝贝儿好3 分钟前
【NLP】第八章:项目实操案例:文本情感分析
人工智能·python·深度学习·算法·自然语言处理
Java面试题总结12 分钟前
Python 文件基本操作
大数据·人工智能·python
buxiangshui_cd12 分钟前
Conda命令
开发语言·python·conda
如竟没有火炬13 分钟前
恢复二叉搜索树
数据结构·数据库·python·leetcode·动态规划
高洁0114 分钟前
从GPT到开源大模型
python·机器学习·数据挖掘·transformer·知识图谱
吴梓穆15 分钟前
Python 基础语法2 if 运算符 循环
android·开发语言·python
如竟没有火炬16 分钟前
整数拆分——动态规划
开发语言·数据结构·python·算法·leetcode·动态规划
叫我:松哥17 分钟前
基于数据挖掘的旅游景点个性化推荐系统设计与实现,Apriori和FP-Growth算法挖掘景点之间的关联规则
人工智能·python·算法·数据挖掘·数据分析·beautifulsoup