当前位置: 首页 > article >正文

LeetCode235. 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, 105].
-109 <= Node.val <= 109
All Node.val are unique.
p != q
p and q will exist in the BST.

二、题解

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(!root) return NULL;
        if(root->val > q->val && root->val > p->val){
            TreeNode* left = lowestCommonAncestor(root->left,p,q);
            if(left) return left;
        }
        else if(root->val < p->val && root->val < q->val){
            TreeNode* right = lowestCommonAncestor(root->right,p,q);
            if(right) return right;
        }
        return root;
    }
};

http://www.kler.cn/a/132049.html

相关文章:

  • 常见面试题-Netty线程模型以及TCP粘包拆包
  • RT-DETR优化改进:轻量级Backbone改进 | VanillaNet极简神经网络模型 | 华为诺亚2023
  • Java使用Redis的几种客户端介绍
  • Python 简易 HTTP 服务器
  • 现有文章汇总
  • Selenium操作已经打开的Chrome浏览器窗口
  • 小数背包问题
  • html所有标签和DOCTYPE的总结
  • iApp祁天社区UI成品源码 功能齐全的社区应用
  • 交换机的工作原理
  • 【SAP-QUERY】QUERY报表的创建
  • SQL ALTER TABLE 语句||SQL AUTO INCREMENT 字段
  • Java排序算法之贪心算法
  • springboot(ssm邮件过滤系统 在线邮箱平台Java(codeLW)
  • 【Linux】Linux进程间通信(三)
  • 信息系统项目管理师 第四版 第5章 信息系统工程
  • 服务器数据恢复—热备盘同步中断导致Raid5数据丢失的数据恢复案例
  • openGauss学习笔记-123 openGauss 数据库管理-设置账本数据库-账本数据库概述
  • 学习css动画-animation
  • 【MySQL】表的增删改查(进阶)