LeetCode //C - 235. Lowest Common Ancestor of a Binary Search Tree

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

Constraints:
  • The number of nodes in the tree is in the range 2 , 1 0 5 2, 10\^5 2,105.
  • − 1 0 9 < = N o d e . v a l < = 1 0 9 -10^9 <= Node.val <= 10^9 −109<=Node.val<=109
  • All Node.val are unique.
  • p != q
  • p and q will exist in the BST.

From: LeetCode

Link: 233. Number of Digit One


Solution:

Ideas:
  • Start from the root and keep traversing the tree.
  • Depending on the values of p and q relative to the current node, move left or right.
  • If you find a node where p and q lie on different sides (or one of them is equal to the current node), that node is the LCA.
Code:
c 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
    while (root != NULL) {
        // If both p and q are greater than root, LCA lies in the right subtree
        if (p->val > root->val && q->val > root->val) {
            root = root->right;
        }
        // If both p and q are smaller than root, LCA lies in the left subtree
        else if (p->val < root->val && q->val < root->val) {
            root = root->left;
        }
        // We have found the split point, i.e. the LCA node
        else {
            return root;
        }
    }
    return NULL; // this line will never be reached if p and q are guaranteed to be in the tree
}
相关推荐
用户老李9 分钟前
卡尔曼滤波自学教程 10:无迹卡尔曼滤波(UKF)
算法
深圳市益普科技有限公司1 小时前
半导体良率管理YMS:良率与设备参数的相关性,先拉哪几组数据
人工智能·python·算法
lhbweilai2 小时前
分析FreeRTOS内核对象API的源码实现(八)
c语言·开发语言·stm32·单片机
程序员清风2 小时前
算法题中的边界条件、测试与调试
开发语言·算法·kotlin
艾络迅Acceleronix3 小时前
环境监测终端:STM32+EG800Z AT+ 艾络迅平台实战|多传感器采集联动全流程
c语言·stm32·单片机·嵌入式硬件·物联网·1024程序员节
炘爚3 小时前
数据结构算法总结
数据结构·python·算法
Zwawa3 小时前
一只按键不只“按下”:短按、长按和连按如何共存
c语言·单片机·嵌入式
Dageno_AI3 小时前
ChatGPT 不再引用 Reddit 之后,还值得在 Reddit 上做 AI 可见度吗?
算法
hetao17338373 小时前
2026-10-25 hetao1733837 的刷题记录
c++·算法
Jsundoku4 小时前
第七章 机器学习 -- 其他经典算法
人工智能·算法·机器学习