leetcode 235: Lowest Common Ancestor of a Binary Search Tree

Python实现最低共同祖先(Lowest Common Ancestor)算法 最低共同祖先(Lowest Common Ancestor,简称LCA)是一种常见的树结构问题,用于确定两个节点在树中的最近公共祖先。在上述示例中,我们创建了一棵二叉树,并查找了节点5和节点1的最低共同祖先。运行代码后,输出将显示"最低共同祖先节点的值为: 3",即节点3为节点5和节点1的最低共同祖先。LCA算法的基本思想是通过树的遍历来确定两个节点的最低共同祖先。我们将首先实现一个二叉树节点的类,用于表示树中的节点。该函数将接受根节点、两个目标节点的值作为参数,并返回它们的最低共同祖先节点。 阅读详情

Lowest Common Ancestor of a Binary Search Tree

Total Accepted: 203 Total Submissions: 511

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allowa node to be a descendant of itself).”

        _______6______
       /              \
    ___2__          ___8__
   /      \        /      \
   0      _4       7       9
         /  \
         3   5

For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

[思路]

如果如果p,q 比root小, 则LCA必定在左子树, 如果p,q比root大, 则LCA必定在右子树. 如果一大一小, 则root即为LCA.

[CODE]

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    //2, 1
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root==null || p==null || q==null) return null;
        
        if(Math.max(p.val, q.val) < root.val) {
            return lowestCommonAncestor(root.left, p, q);
        } else if(Math.min(p.val, q.val) > root.val) {
            return lowestCommonAncestor(root.right, p, q);
        } else return root;
    }
}

这道题还可以有一个followup. 如果是普通二叉树, 而不是BST.  则应该遍历节点, 先找到p,q. 同时记录下从root到该几点的路径.   之后比较路径,最后一个相同的节点便是LCA.

[CODE]

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    //2, 1
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root==null || p==null || q==null) return null;
        
        List<TreeNode> pathp = new ArrayList<>();
        List<TreeNode> pathq = new ArrayList<>();
        pathp.add(root);
        pathq.add(root);
        
        getPath(root, p, pathp);
        getPath(root, q, pathq);
        
        TreeNode lca = null;
        for(int i=0; i<pathp.size() && i<pathq.size(); i++) {
            if(pathp.get(i) == pathq.get(i)) lca = pathp.get(i);
            else break;
        }
        return lca;
    }
    
    private boolean getPath(TreeNode root, TreeNode n, List<TreeNode> path) {
        if(root==n) {
            return true;
        }
        
        if(root.left!=null) {
            path.add(root.left);
            if(getPath(root.left, n, path)) return true;
            path.remove(path.size()-1);
        }
        
        if(root.right!=null) {
            path.add(root.right);
            if(getPath(root.right, n, path)) return true;
            path.remove(path.size()-1);
        }
        
        return false;
    }
}


OpenClaw 企业级自动化系统架构设计与实现 本文介绍基于 OpenClaw 构建的企业级自动化系统的完整架构设计、技术选型、实现细节和性能优化方案。 阅读详情

相关推荐

实验手册(灾难恢复)

我们发现DC1与DC2的复制出现问题,此时我们检查了在DC2中,DC1是否被正确注册。这里选择还原系统状态,因为我们原DC1上只备份了AD的数据,所以我们在新的这台服务器上还原的也是AD数据库。因为我们是单域下的测试,只测试了一个域,所以它会出现这样的报错。我们选择远程共享文件夹,我们备份的时候,是在备份这台服务器上的。同时删除SRV记录,A记录,NS记录,SOA记录,框框里面的所有有关dc1的记录全部删除。如果在企业中AD数据的备份是每周或者每月都会有一次备份,选择恢复AD数据库的时间。

weixin_52364868的博客 1313

leetcode:235. Lowest Common Ancestor of a Binary Search Tree

个人学习笔记:在二叉搜索树中寻找最低共同父节点 很简单的题目,直接贴代码 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), le

u010016196的专栏 393

lerobot VLA--SmolVLA代码的讲解

2.图像resize至正方形224x224,图像长宽比不变,其他区域用黑色补充,标记为mask=1,若占位图像(摄像头缺失),则 创建全-1像素的占位图像 标记为mask=0,image为[1, 3, 512, 512],img_mask为True,masks列表长度为2,img_masks为2,因为我这里两个相机。文本嵌入:通过embed_language_tokens() 被转换为嵌入表示,lang_emb 是语言的嵌入,包含了语言的语法和语义信息。1.像素值[0,1]->[-1,1]

caokaifa的博客 4093

235. Lowest Common Ancestor of a Binary Search Tree*

235. Lowest Common Ancestor of a Binary Search Tree* https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/ 题目描述 Given a binary search tree (BST), find the lowest common ancesto...

珍妮的选择的博客 327

Openclaw Onboarding向导全攻略——如何配置你的第一个AI助手

很多新手在成功运行 `openclaw --version` 后,面对黑底白字的终端就陷入了迷茫:“安装好了,然后呢?” 本篇我们就彻底解决这个问题,带你完整走完 `openclaw onboard` 交互式初始化配置向导的每一步,从“安装完成”到“真正能用”,只差这一个向导的距离。 本文为2026年3月最新版,适配OpenClaw v2026.2.x 稳定版,所有步骤均经过实测验证,可直接落地。

夏日清风 1942

病理组学分析系列教程1:使用Python-histolab进行病理图像预处理,tiles切片自动生成

病理图像tiles自动生成,WSI图像预处理

qq_43449643的博客 1749

lc235. Lowest Common Ancestor of a Binary Search Tree

235. Lowest Common Ancestor of a Binary Search Tree Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikiped...

weixin_34303897的博客 151

Python新手必看:5分钟搞定睿尔曼机械臂基础控制(附代码示例)

本文为Python新手提供了快速上手睿尔曼机械臂基础控制的实战指南。通过详细的步骤讲解和代码示例,介绍了从环境搭建、网络配置、SDK安装到建立连接、执行关节运动(movej)、直线运动(movel)等核心控制指令的全过程,帮助零基础开发者快速实现机械臂的基础操控。

hp777的博客 337

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 and as the lowest node in that has both

kduduuuw的博客 934

Agent智能体:核心概念与架构——建立系统认知

本文摘要介绍了Agent智能体的核心概念与架构设计。主要内容包括: Agent定义与分类:阐述了Agent作为能够感知环境、决策执行的智能实体,重点分析了现代基于大语言模型(LLM)的Agent架构。 核心模块组成:详细说明了Agent的五大核心模块(感知、规划、记忆、工具和执行)及其交互流程。 UML建模展示:通过类图和序列图,清晰呈现了Agent系统的静态结构和动态执行过程。 项目结构设计:给出了模块化的代码目录结构,为实际开发提供参考框架。

lza_csdn2019的博客 640

基于XGBoost的混凝土力学性能预测系统

本文介绍了一个基于XGBoost算法的混凝土力学性能预测系统。该系统通过模拟生成3000组混凝土配合比数据(包含水灰比、水泥用量和龄期三个关键特征),利用XGBoost强大的非线性建模能力预测混凝土抗压强度。研究背景源于传统混凝土性能测试方法耗时耗力的痛点,该系统可显著减少实验次数,优化配合比设计。系统实现包括:数据生成与特征工程(模拟真实工程数据并添加噪声和异常值)、XGBoost模型构建、以及预测性能评估。XGBoost算法因其处理非线性关系能力强、鲁棒性好等优势被选用,可为智能建造和数字化施工提供技术

huanghm88的专栏 133

LeetCode 235: Lowest Common Ancestor of a Binary Search Tree

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined betwee

哈哈的个人专栏 2816

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

LeetCode: 235. Lowest Common Ancestor of a Binary Search Tree

LeetCode: 235. Lowest Common Ancestor of a Binary Search Tree 题目描述 Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of...

杨领well的专栏 210

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

LeetCode 235:Lowest Common Ancestor of a Binary Search Tree

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined betw

judadeshu的博客 281

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

leetcode: 235. Lowest Common Ancestor of a Binary Search Tree

题目: Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined betw...

makerjj的博客 278

leetcode235:Lowest Common Ancestor of a Binary Search Tree

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined betw

y_d_f_qing2010的专栏 183

LeetCode笔记:235. Lowest Common Ancestor of a Binary Search Tree

找出一个二叉查找树中两个节点的最低共同祖先

Minecraft 1122

leetcode[235]:Lowest Common Ancestor of a Binary Search Tree

Lowest Common Ancestor of a Binary Search Tree Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.According to the definition of LCA on Wikipedia: “Th

hahubaba的博客 308

Leetcode:235. Lowest Common Ancestor of a Binary Search Tree(JAVA)

【问题描述】 Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is de

莫名的程序猿 343

Leetcode学习笔记:#235. Lowest Common Ancestor of a Binary Search Tree

Leetcode学习笔记:#235. Lowest Common Ancestor of a Binary Search Tree Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of ...

ccystewart的博客 185

Leetcode 235: Lowest Common Ancestor of a Binary Search Tree

问题描述: Given a binary search tree (BST), find the lowest common ancestor (LCA) 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

weixin_51401145的博客 131
上一篇: leetcode 233: Number of Digit One
下一篇: leetcode 236: Lowest Common Ancestor of a Binary Tree
xudli
博客等级 码龄18年 204粉丝 275原创
评论 8
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值