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
}
相关推荐
成宏爸4 分钟前
【字幕】恋上数据结构与算法之015动态数组03简单接口的实现
数据结构·算法
Lenyiin14 分钟前
3286、穿越网格图的安全路径
c++·算法·leetcode
螺蛳粉只吃炸蛋的走风21 分钟前
面试题总结(三) -- 内存管理篇
c语言·c++·面试·内存·堆栈·raii
爱是小小的癌24 分钟前
C语言自定义类型-联合与枚举
c语言·开发语言
临沂堇27 分钟前
CCF刷题计划——阴阳龙(八方最近点)
算法
轩源源41 分钟前
C/C++内存管理
c语言·开发语言·数据结构·c++·算法·缓存·内存空间的开创
人才程序员1 小时前
CSP-J 算法基础 图论
开发语言·数据结构·c++·算法·青少年编程·图论·编程比赛
微学AI1 小时前
机器学习实战21-基于XGBoost算法实现糖尿病数据集的分类预测模型及应用
算法·机器学习·分类·糖尿病
热爱编程的OP1 小时前
图论篇--代码随想录算法训练营第五十八天打卡|拓扑排序,dijkstra(朴素版),dijkstra(堆优化版)精讲
数据结构·c++·算法·图论
bluebonnet271 小时前
【Rust练习】14.流程控制
开发语言·c++·后端·算法·rust