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)."

Example 1:

复制代码
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6
Explanation: The LCA of nodes 2 and 8 is 6.

Example 2:

复制代码
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
Output: 2
Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

Example 3:

复制代码
Input: root = [2,1], p = 2, q = 1
Output: 2

Intuition

The goal is to find the lowest common ancestor (LCA) of two given nodes in a binary search tree (BST). The intuition is to exploit the properties of a BST, where nodes in the left subtree are smaller than the root, and nodes in the right subtree are larger than the root. By comparing the values of the nodes p and q with the value of the current root, we can determine the location of the LCA.

Approach

Traversal:

Start with the root of the BST.

While traversing the tree:

If both p and q are greater than the current root's value, move to the right subtree.

If both p and q are smaller than the current root's value, move to the left subtree.

If the current root's value is between p and q, or if it is equal to either p or q, then the current root is the LCA. Return the current root.

Return Result:

Return the final result, which is the lowest common ancestor of p and q.

Complexity

  • Time complexity:

The time complexity is O(h), where h is the height of the binary search tree. In the average case, for a balanced BST, the height is O(log n), making the time complexity O(log n). However, in the worst case of an unbalanced tree, the height could be O(n), resulting in a time complexity of O(n).

  • Space complexity:

The space complexity is O(1) since no additional data structures are used that scale with the input size. The algorithm uses a constant amount of space to store the current root and temporary variables.

Code

# 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 root.val < p.val and root.val < q.val:
                root = root.right
            
            elif root.val > p.val and root.val > q.val:
                root = root.left
            
            else:
                return root
        return None
相关推荐
不去幼儿园3 分钟前
【启发式算法】Dijkstra算法详细介绍(Python)
人工智能·python·算法·机器学习·启发式算法·图搜索算法
serve the people11 分钟前
神经网络中梯度计算求和公式求导问题
神经网络·算法·机器学习
闻缺陷则喜何志丹17 分钟前
【二分查找、滑动窗口】P10389 [蓝桥杯 2024 省 A] 成绩统计|普及+
c++·算法·蓝桥杯·二分查找·滑动窗口·洛谷·成绩
乔冠宇1 小时前
蓝桥杯算法——铠甲合体
算法·职场和发展·蓝桥杯
商bol451 小时前
算阶,jdk和idea的安装
数据结构·c++·算法
迷迭所归处1 小时前
C语言 —— 愿文明如薪火般灿烂 - 函数递归
c语言·开发语言·算法
柠檬鲨_4 小时前
C语言100天练习题【记录本】
c语言·数据结构·算法
float_六七4 小时前
二叉树三种遍历方式——前序、中序、后序(C++)
开发语言·c++·算法
CYRUS_STUDIO9 小时前
常用加解密算法介绍
算法·安全·逆向
weixin_5358542211 小时前
快手,蓝禾,优博讯,三七互娱,顺丰,oppo,游卡,汤臣倍健,康冠科技,作业帮,高途教育25届春招内推
java·前端·python·算法·硬件工程