235. Lowest Common Ancestor of a Binary Search Tree [easy] (Python)

【漏洞复现】7-Zip目录穿越漏洞(CVE-2025-11001) 摘要:CVE-2025-11001是7-Zip(v21.02-v24.09)Windows版处理ZIP包符号链接时的高危漏洞,攻击者可构造恶意ZIP文件实现目录穿越和任意文件写入。漏洞源于路径检查缺陷,当用户解压含特殊符号链接的压缩包时,可能将文件写入系统目录。复现利用GitHub公开的Python脚本(https://github.com/pacbypass/CVE-2025-11001)可生成攻击包,需注意该漏洞仅影响Windows且需要用户交互。 阅读详情

题目链接

https://leetcode.com/problems/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 v and w as the lowest node in T that has both v and w as descendants (where we allow a 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.

题目翻译

思路方法

思路一

根据二叉搜索树的性质,对于树中从root开始的节点:
如果p和q的值如果都小于root的值,那么它们的最低公共祖先一定在root的左子树;如果p和q的值如果都大于root的值,那么它们的最低公共祖先一定在root的右子树;其他情况则说明最低公共祖先就是root节点。如此循环判断即可。

代码

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        pointer = root
        while pointer:
            if p.val > pointer.val and q.val > pointer.val:
                pointer = pointer.right
            elif p.val < pointer.val and q.val < pointer.val:
                pointer = pointer.left
            else:
                return pointer

思路二

类似前面的思路,不过是用递归实现。

代码

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        if not root:
            return None
        if p.val < root.val and q.val < root.val:
            return self.lowestCommonAncestor(root.left, p, q)
        elif p.val > root.val and q.val > root.val:
            return self.lowestCommonAncestor(root.right, p, q)
        else:
            return root

思路三

更通用的做法是,先分别找到从根节点到两个节点的路径,根据这两个路径找最低公共祖先。方便的是,对于二叉搜索数,不需要BFS或DFS遍历节点找路径。

代码

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        pathp = self.findPath(root, p)
        pathq = self.findPath(root, q)
        res = root
        for i in xrange(1, min(len(pathp), len(pathq))):
            if pathp[i] == pathq[i]:
                res = pathp[i]
        return res


    def findPath(self, root, p):
        path = []
        while root.val != p.val:
            path.append(root)
            if p.val > root.val:
                root = root.right
            elif p.val < root.val:
                root = root.left
        path.append(p)
        return path

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/51498796

PyCharm 2023最新版安装配置全攻略(附永久激活教程) 本文详细介绍了PyCharm 2023最新版的安装配置全流程,包括版本选择、初始配置、插件生态、工程模板、调试优化及团队协作等关键步骤。特别针对专业版和社区版的功能差异进行对比,帮助开发者高效搭建Python开发环境,提升编码效率与团队协作能力。 阅读详情

相关推荐

当迁移学习遇见室内定位:基于UJIIndoorLoc的跨场景适配实践

本文探讨了迁移学习在跨建筑室内定位中的应用,重点解析了UJIIndoorLoc数据集的特性及其在解决设备差异和环境变化中的关键作用。通过特征工程、迁移学习策略和小样本微调技术,显著提升了定位模型的跨场景适配能力,为实际部署提供了有效解决方案。

weixin_29038155的博客 399

LeetCode:236. Lowest Common Ancestor of a Binary Tree(二叉树中最小祖先)

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

zy345293721的博客 314

YOLOv8实战火焰和烟雾检测 (视频教程)

本课程将手把手地教大家使用YOLOv8结合可变形卷积(deformable convolution)训练火焰和烟雾数据集,完成一个多目标检测实战项目,可实时检测图像、视频、摄像头和流媒体(http/rtsp)中火焰和烟雾,并提供可视化演示界面 。

bai666ai的博客 1922

二叉树的最近公共祖先(lowest-common-ancestor-of-a-binary-tree)

目录题目代码与思路前序遍历,中序遍历,后序遍历 题目 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。” 例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4]...

mirana的专栏 403

使用sklearn学习多项式回归(三)

1,什么是线性 我们无数次提到”线性“这个名词。在支持向量机中,我们也曾经提到最初的支持向量机只能够分割线性可分的数据,然后引入了”核函数“来帮助我们分类那些非线性可分的数据。我们也曾经说起过,比如说决策树,支持向量机是”非线性“模型。所有的这些概念,让我们对”线性“这个词非常熟悉,却又非常陌生——因为我们并不知道它的真实含义。接下来我们看看线性回归模型改进的核心之一:帮助线性回归解决非线性问题。 1.1,变量之间的线性关系 ”线性“这个词用于描述不同事物时有着不同的含义。我们最常使用的线性是指“变量

理科男同学 5107

从C到汇编:单片机汇编语言核心概念迁移指南

本文详细介绍了从C语言迁移到单片机汇编语言的核心概念与实践指南,特别适合嵌入式开发者。文章深入探讨了汇编语言在性能优化、时序控制等方面的独特优势,并提供了变量存储、函数实现、流程控制等关键概念的对应关系,帮助开发者高效掌握汇编编程技巧。

weixin_31887307的博客 347

【Python Leetcode】236. Lowest Common Ancestor of a Binary Tree

python leetcode 236 LCA的解法

jessie_31655616的博客 625

Flightmare实战:从零搭建强化学习无人机控制环境

本文详细介绍了从零开始搭建Flightmare强化学习无人机控制环境的完整流程。内容包括环境准备、核心库安装、依赖冲突解决,以及如何运行PPO算法示例进行训练与可视化测试。文章还提供了环境配置、自定义任务修改及常见问题的避坑指南,帮助开发者快速上手这一模块化的无人机RL仿真平台。

weixin_29081101的博客 361

LeetCode236. Lowest Common Ancestor of a Binary Tree(思路及python解法)

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

AIpush的博客 431

V-REP(Cooprliesim EDU)自学笔记 实现UR5机械臂末端按轨迹移动

V-REP(Cooprliesim EDU)自学笔记 实现UR5机械臂末端按轨迹移动

xu_white的博客 7586

腾讯开源SuperSonic:AI+BI如何重塑数据分析?

SuperSonic是腾讯开源的AI+BI平台,融合Chat BI与Headless BI,为制造企业提供实时数据分析。它通过自然语言交互打破数据壁垒,实现生产、库存、质量、供应链等多环节优化,提升决策效率,其开源生态与扩展性助力企业数字化转型与数据价值挖掘。

数据与算法架构提升之路专栏 4562

leetcode 236. Lowest Common Ancestor of a Binary Tree 二叉树的最近公共祖先(中等)

这是 二叉搜索树的最近公共祖先 这题的衍生题,这道题是普通的二叉树,不是二叉搜索树,所以就不能利其特有的性质,只能在二叉树中来搜索p和q,然后从路径中找到最后一个相同的节点即为父节点,可以用递归来实现,在递归函数中,首先看当前节点是否为空,若为空则直接返回空;若为p或q中的任一个,也直接返回当着节点;否则的话就对其左右子节点分别调用递归函数。

ln_ydc的专栏 729

[特殊字符] PetaLinux Qt 程序(WindRadar)无法自动启动问题解决文档

摘要:本文档解决了PetaLinux 2020.1系统中Qt程序(WindRadar)无法开机自动显示界面的问题。通过分析发现,自动启动时缺少DISPLAY=:0.0环境变量导致Qt找不到显示设备。最终在autostart.sh脚本中添加该变量,并完善了字体加载、驱动加载、显示设备检测等流程,确保程序正常自启显示界面。完整脚本包含路径检测、环境配置和错误处理,经验证各项功能均正常运行。

梁俊星的博客 334

python --- 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 betwe...

不服输的南瓜的博客 338

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

235. Lowest Common Ancestor of a Binary Search Tree(Tree-Easy)

求二叉树的LCA,也就是两个节点的最低公共祖先。

Jack-Cui 4910

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

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

每天都要有进步 248

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

【LeetCode】235. Lowest Common Ancestor of a Binary Search Tree 解题报告(Java & Python)

Lowest Common Ancestor of a Binary Search Tree[LeetCode]https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/Total Accepted: 67533 Total Submissions: 178900 Difficulty: EasyQues

负雪明烛 2036

leetcode 235 lowest-common-ancestor-of-a-binary-search-tree 二叉搜索树的最近公共祖先 python3

时间:2020-05-30 题目地址:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree/ 题目难度:Easy 题目描述: 给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。” 例如,给定如下二

isabloomingtree的博客 206

LeetCode236 - 二叉树的最近公共祖先

原题 https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/ 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。” 例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4] 示例 1

Kuls 489

Lowest Common Ancestor of a Binary Tree

题目地址:点击打开链接 解法一:对于深度过高的case过不了。 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NU

578

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的专栏 392

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

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

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

236. Lowest Common Ancestor of a Binary Tree

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

zuisixian的博客 252

235. Lowest Common Ancestor of a Binary Search Tree

235. Lowest Common Ancestor of a Binary Search Tree方法1: recursionComplexity易错点:方法2: iterative Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. Acc...

wilzxu的博客 119
上一篇: 350. Intersection of Two Arrays II [easy] (Python)
下一篇: 326. Power of Three [easy] (Python)
coder_orz
博客等级 码龄14年 102粉丝 90原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值