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
相关推荐
17(无规则自律)1 分钟前
DFS连通域统计:岛屿数量问题及其变形
c++·算法·深度优先
ZC跨境爬虫5 分钟前
极验滑动验证码自动化实战(ddddocr免费方案):本地缺口识别与Playwright滑动模拟
前端·爬虫·python·自动化
笨笨饿17 分钟前
34_数据结构_栈
c语言·开发语言·数据结构·人工智能·嵌入式硬件·算法
单片机学习之路29 分钟前
【Python】输入print函数
开发语言·前端·python
后藤十八里29 分钟前
极验4消消乐验证码逆向笔记
笔记·爬虫·python
im_AMBER29 分钟前
Leetcode 152 被围绕的区域 | 岛屿数量
数据结构·算法·leetcode·深度优先·广度优先·图搜索算法
李昊哲小课34 分钟前
Python办公自动化教程 - 第1章 openpyxl基础入门 - 第一次用代码操控Excel
开发语言·python·excel·openpyxl
智算菩萨37 分钟前
【Python图像处理】4 NumPy数组操作与图像矩阵运算
图像处理·python·numpy
SomeB1oody37 分钟前
【Python深度学习】1.1. 多层感知器MLP(人工神经网络)介绍
开发语言·人工智能·python·深度学习·机器学习
数据科学小丫40 分钟前
数据分析利器 Pandas :apply() 方法 + map() 配对 + 计算描述统计 + 协方差和相关性 + 异常值处理常用方法(基于 python )
python·数据分析·numpy·pandas