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
}
相关推荐
毅炼5 小时前
今日LeetCode 摸鱼打卡
java·算法·leetcode
m0_629494736 小时前
LeetCode 热题 100-----28. 两数相加
数据结构·算法·leetcode·链表
菜菜的顾清寒6 小时前
力扣HOT100(25)环形链表
算法·leetcode·链表
学不懂飞行器6 小时前
【2024电赛H题硬核解析】自动行驶小车满分对策:多路灰度循迹与陀螺仪“交替盲走”融合算法(附源码)
stm32·单片机·嵌入式硬件·算法·电赛
机器学习之心6 小时前
大跨度拱桥施工智能优化:基于改进RBF神经网络与多目标算法的工程实践
人工智能·神经网络·算法·大跨度拱桥施工智能优化
Deep-w6 小时前
【MATLAB】基于 MATLAB/Simulink 的无刷直流电机(BLDC)转速控制模糊 PID 算法
开发语言·算法·matlab
皮卡祺q6 小时前
【算法-0】背包问题(三维+二维)
java·javascript·算法
葫三生6 小时前
《论三生原理》对《周易》《道德经》的一次根本性重写?
人工智能·算法·计算机视觉·区块链·量子计算
心中有国也有家6 小时前
ascend-boost-comm:一次写完,到处复用——算子公共平台的 M×N 哲学
人工智能·经验分享·笔记·分布式·算法
AI科技星6 小时前
空间圆柱螺旋运动第一性原理终极推导·证明·核验·全量纲闭环
开发语言·人工智能·算法·计算机视觉·量子计算