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
}
相关推荐
xiaoshiguang31 小时前
LeetCode:77. 组合
java·算法·leetcode
lzb_kkk3 小时前
【C++】C++11异步操作
c语言·开发语言·c++·1024程序员节
Ning_.5 小时前
LeetCode 第367题:有效的完全平方数
算法·leetcode·职场和发展
今天吃饺子6 小时前
小创新模型!6种2024算法优化BiTCN-SVM单变量输入单步预测,MATLAB机器学习预测全家桶再更新...
人工智能·算法·机器学习·支持向量机·matlab
廖显东-ShirDon 讲编程7 小时前
《零基础Go语言算法实战》【题目 2-5】函数参数的值传递和引用传递
算法·程序员·go语言·web编程·go web
不玩return的马可乐7 小时前
LeetCode 747. 至少是其他数字两倍的最大数
数据结构·c++·程序人生·算法·leetcode
bgf_me8 小时前
代码随想录算法训练营第三十二天|509.斐波那契数、70.爬楼梯、746.使用最小花费爬楼梯
算法
怎么名字都重复8 小时前
1.两数之和--力扣
java·数据结构·算法·leetcode·软件工程
Odaily_8 小时前
SVM赛道概览:MoveVM落地,SVM能走多远
人工智能·算法·机器学习·支持向量机·数据挖掘
深图智能8 小时前
OpenCV的一种改进型的素描特效算法
图像处理·opencv·算法·计算机视觉