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
相关推荐
cpp_25015 小时前
P1024 [NOIP 2001 提高组] 一元三次方程求解
数据结构·c++·算法·题解·二分答案·洛谷·csp
2401_846339566 小时前
CSS如何优化大型项目样式_使用SASS预处理器提升开发效率
jvm·数据库·python
田梓燊12 小时前
力扣:23.合并 K 个升序链表
算法·leetcode·链表
invicinble12 小时前
这里对java的知识体系做一个全域的介绍
java·开发语言·python
re林檎12 小时前
算法札记——4.27
算法
m0_6742946413 小时前
如何编写SQL存储过程性能对比_记录执行时间评估优化效果
jvm·数据库·python
数据牧羊人的成长笔记13 小时前
逻辑回归与Softmax回归
算法·回归·逻辑回归
运气好好的13 小时前
怎样开启phpMyAdmin的操作审计日志_记录每条执行的SQL
jvm·数据库·python
郑州光合科技余经理13 小时前
同城O2O海外版二次开发实战:从支付网关到配送算法
开发语言·前端·后端·算法·架构·uni-app·php
2401_8714928514 小时前
Layui如何修改Layui默认的UI主题颜色(换肤功能实现)
jvm·数据库·python