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
}
相关推荐
坚持不懈的大白3 分钟前
leetcode学习笔记2
笔记·学习·leetcode
枫叶丹44 分钟前
【Qt开发】Qt系统(十)-> Qt HTTP Client
c语言·开发语言·网络·c++·qt·http
范纹杉想快点毕业5 分钟前
自学嵌入式系统架构设计:有限状态机入门完全指南,C语言,嵌入式,单片机,微控制器,CPU,微机原理,计算机组成原理
c语言·开发语言·单片机·算法·microsoft
星火开发设计3 小时前
枚举类 enum class:强类型枚举的优势
linux·开发语言·c++·学习·算法·知识
爱编码的小八嘎8 小时前
C语言对话-10.关于操纵器的对话
c语言
嘴贱欠吻!9 小时前
Flutter鸿蒙开发指南(七):轮播图搜索框和导航栏
算法·flutter·图搜索算法
张祥6422889049 小时前
误差理论与测量平差基础笔记十
笔记·算法·机器学习
踩坑记录9 小时前
leetcode hot100 2.两数相加 链表 medium
leetcode·链表
qq_192779879 小时前
C++模块化编程指南
开发语言·c++·算法
cici1587411 小时前
大规模MIMO系统中Alamouti预编码的QPSK复用性能MATLAB仿真
算法·matlab·预编码算法