首页 > 其他分享 >235. Lowest Common Ancestor of a Binary Search Tree[Medium]

235. Lowest Common Ancestor of a Binary Search Tree[Medium]

时间:2023-02-07 10:56:22浏览次数:43  
标签:Lowest Binary Search TreeNode val BST nodes root 节点

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).”

Constraints:

  • The number of nodes in the tree is in the range [2, 105].
  • -10^9 <= Node.val <= 10^9
  • All Node.val are unique.
  • p != q
  • p and q will exist in the BST.

Example
image

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.

题解

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        // BST特性 左子树小于当前节点,右子树大于当前节点
        // 所以如果要找的两个节点都小于当前节点,那就去左子树里继续找
        if (p.val < root.val && q.val < root.val)
            return lowestCommonAncestor(root.left, p, q);
        // 如果都大于当前节点,那就去右子树里找
        if (p.val > root.val && q.val > root.val)
            return lowestCommonAncestor(root.right, p, q);

        // 如果都不满足,那当前节点就是公共祖先节点了
        return root;
    }

标签:Lowest,Binary,Search,TreeNode,val,BST,nodes,root,节点
From: https://www.cnblogs.com/tanhaoo/p/17097621.html

相关文章

  • 使用Kubernetes搭建带有ik分词的Elasticsearch集群
    创建好带有Ik分词的es镜像,并上传到镜像仓库中,创建镜像可参考链接中的文档https://www.cnblogs.com/hi-lijq/p/16895206.html编写es_cluster-ik-config.yaml文件apiVe......
  • Anchor-Free Person Search
    将主要问题总结为不同层次(规模、区域和任务)的错位问题设计了alignedfeatureaggregation(AFA)module,遵循"re-idfirst"原则AFA通过利用deformableconvolution和特征......
  • 2331.evaluate-boolean-binary-tree 计算布尔二叉树的值
    问题描述2331.计算布尔二叉树的值解题思路递归代码classSolution{public:booldfs(TreeNode*root){if(root->left==nullptr){re......
  • Yum 安装 Elasticsearch + Kibana教程
    Yum安装Elasticsearch+Kibana教程安装Elasticsearch准备elasticsearch(下面称为ES)是一个基于Lucene的搜索服务器。所以他需要java的环境即jdk#yuminstalljava*#vim......
  • elasticsearch高可用 原理
    elasticsearch高可用原理 ES是如何解决高可用ES是一个分布式全文检索框架,隐藏了复杂的处理机制,核心数据分片机制、集群发现、分片负载均衡请求路由。ES的高可用架构......
  • elasticsearch高可用 原理
    elasticsearch高可用原理 ES是如何解决高可用ES是一个分布式全文检索框架,隐藏了复杂的处理机制,核心数据分片机制、集群发现、分片负载均衡请求路由。ES的高可用架构......
  • [LeetCode] 2331. Evaluate Boolean Binary Tree
    Youaregiventhe root ofa fullbinarytree withthefollowingproperties:Leafnodes haveeitherthevalue 0 or 1,where 0 represents False and......
  • 使用kibana来进行ElasticSearch的信息查询检索
    大家经常会听到使用ELK搭建日志管理平台、完成日志聚合检索的功能,那么这个平台到底是个什么概念,怎么搭建,怎么使用呢?ELK包括ElasticSearch(数据存储、快速查询)、logstash(日志......
  • ElasticSearch分布式搜索引擎——从入门到精通
    ES分布式搜索引擎注意:在没有创建库的时候搜索,ES会创建一个库并自动创建该字段并且设置为String类型也就是text什么是elasticsearch?一个开源的分布式搜索引擎,可以用......
  • php操作ElasticSearch搜索引擎流程详解
    目录一、安装二、使用三、新建ES数据库四、创建表五、插入数据六、查询所有数据七、查询单条数据八、搜索九、测试代码〝古人学问遗无力,少壮功夫老始成〞......