Tree_Graph LCA(Lowest Common Ancestor) 最低公共节点 (BST或者一般树) @CareerCup

【实战教程】BMAD-METHOD 入门教程:用 AI 组建你的“七人开发团队” 简单说,BMAD-METHOD 就像一个会自己运转的“AI 软件公司”。它不是某个单一应用,而是一种AI 工作流方法论—— 把一个项目拆解成多个角色(产品、架构、前后端、测试、运维等),每个角色由一个 AI 智能体负责协作,就像你真的在带一个 7 人团队。GitHub 项目地址 👉目前 Star 数已经达到了恐怖的 20k,可见这套方法的影响力不小。BMAD-METHOD 的核心理念不是“生成代码”,而是“自动化协作”。 阅读详情

原文:

Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. Avoid storing additional nodes in a data structure. NOTE: This is not necessarily a binary search tree.

译文:

写程序在一棵二叉树中找到两个结点的第一个共同祖先。不允许存储额外的结点。注意: 这里不特指二叉查找树。


思路:

其实没有什么难得,入手点就是分情况,搞清楚p,q能在树的位置的各种情况。

我们可以从根结点开始,判断以当前结点为根的树中左右子树是不是包含我们要找的两个结点。如果两个结点都出现在它的左子树中,那最低的共同父结点也出现在它的左子树中。如果两个结点都出现在它的右子树中,那最低的共同父结点也出现在它的右子树中。如果两个结点一个出现在左子树中,一个出现在右子树中,那当前的结点就是最低的共同父结点


package Tree_Graph;

import CtCILibrary.TreeNode;

public class S4_7 {

	
	// ========================= 未优化递归版
	// 递归求公共祖先,Time:O(N)
	public static TreeNode commonAncestor(TreeNode root, TreeNode p, TreeNode q) {
		// 错误判断,如果有一个点根本不在树内,则报错!
		if(!isIn(root.left, p) || !isIn(root.right, q)) {
			return null;
		}
		return commonAncestorRec(root, p, q);
	}
	
	public static TreeNode commonAncestorRec(TreeNode root, TreeNode p, TreeNode q) {
		if(root == null) {
			return null;
		}
		if(root==p || root==q) {
			return root;
		}
		
		boolean isPInLeft = isIn(root.left, p);		// 判断p是否在树的左侧
		boolean isQInLeft = isIn(root.left, q);		// 判断q是否在树的左侧
		
		if(isPInLeft != isQInLeft){			// 如果一个在左侧一个在右侧,则公共祖先必然是root
			return root;
		}
		
		if(isPInLeft) {		// p,q都在左侧
			return commonAncestorRec(root.left, p, q);
		} else{				// p,q都在右侧
			return commonAncestorRec(root.right, p, q);
		}
	}
	
	// 判断节点p是否在root树中
	private static boolean isIn(TreeNode root, TreeNode node) {
		if(root == null) {
			return false;
		}
		if(root == node) {
			return true;
		}
		return isIn(root.left, node) || isIn(root.right, node);
	}
	
	
	
	// ========================= 优化递归版,待改动
	public static TreeNode commonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
		Result res = commonAncestorRec2(root, p, q);
		if(res.isAncestor) {
			return res.node;
		}
		return null;
	}
	
	public static Result commonAncestorRec2(TreeNode root, TreeNode p, TreeNode q) {
		if(root == null) {
			return new Result(null, false);
		}
		if(root==p && root==q) {
			return new Result(root, true);
		}
		
		Result leftRes = commonAncestorRec2(root.left, p, q);
		if(leftRes.isAncestor) {		// 在左子树找到公共节点
			return leftRes;
		}
		
		Result rightRes = commonAncestorRec2(root.right, p, q);
		if(rightRes.isAncestor) {	// 在右子树找到公共节点
			return rightRes;
		}
		
		if(leftRes.node!=null && rightRes.node!=null) {
			return new Result(root, true);		// root为公共节点
		} 
		else if(root==p || root==q) {
			boolean isAncestor = (leftRes.node != null || rightRes.node != null) ? true : false;
			return new Result(root, isAncestor);
		} 
		else {
			return new Result(leftRes!=null ? leftRes.node : rightRes.node, false);
		}
	}
	
	static class Result {
		public TreeNode node;
		public boolean isAncestor;
		public Result(TreeNode n, boolean isAnc) {
			node = n;
			isAncestor = isAnc;
		}
	}
	
	
	public static void main(String[] args) {
		int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
		TreeNode root = TreeNode.createMinimalBST(array);
		TreeNode n3 = root.find(1);
		TreeNode n7 = root.find(7);
		TreeNode ancestor = commonAncestor(root, n3, n7);
		System.out.println(ancestor.data);
	}
}


Follow Up:

假如这棵树是BST,那么怎么做?

就不必用isIn函数了,直接把待判断节点的值与root相比较即可,下面写了递归和非递归版解法:


public class TreeNode {
    int data;
    TreeNode left, right;
}

// 递归 Time Complexity: O(h) h: 树高
// Space complexity: O(n) n:节点个数
public TreeNode lca(TreeNode root, TreeNode p, TreeNode q) {
    if(root == null) {
        return null;
    }
    if(p.data < root.data && q.data < root.data) {
        return lca(root.left, p, q);
    }
    if(p.data > root.data && q.data > root.data) {
        return lca(root.right, p, q);
    }
    return root;
}


// Iteration不用递归
// Time Complexity: O(h) h: 树高
// Space complexity: O(1) 
public TreeNode lca2(TreeNode root, TreeNode p, TreeNode q) {
    if(root == null) {
        return null;
    }
    while(root != null) {
        if(p.data < root.data && q.data < root.data) {    // p,q都在左子树
            return lca(root.left, p, q);
        }
        else if(p.data > root.data && q.data > root.data) {   // p,q都在右子树
            return lca(root.right, p, q);
        }
        else {        // p,q分别在不同子树
            break;
        }
    }
    return root;
}





Ref:

http://zhedahht.blog.163.com/blog/static/25411174201081263815813/

http://hawstein.com/posts/4.6.html

http://www.geeksforgeeks.org/lowest-common-ancestor-in-a-binary-search-tree/

YOLOv11改进 | Neck篇 | 独创HFPN利用分层特征融合块HFFB模块融合多层次特征改进yolov11(全网独家创新) 本文给大家带来的最新改进是利用分层特征融合块HFFB创新yolov11的neck部分我称之为HFPN,这个模块可以融合局部特征、全局特征、中间特征将三种特征融合在一起辅助yolov11进行检测,经过我的设计分为三种可以针对大目标、小目标、标准目标的检测方式均不同,大家可以根据自己的数据集进行不同的选择,本文的内容为我独家创新。YOLOv11改进系列专栏——本专栏持续复习各种顶会内容——科研必备目录一、本文介绍二、原理介绍三、核心代码四、添加方法4.1 修改一4.2 修改二4.3 修改三4.4 修改四。 阅读详情

相关推荐

Win11 C盘爆满别慌!手把手教你安全迁移AppData和用户文件夹(附一键脚本)

本文针对Win11 C盘空间不足问题,提供了一套安全有效的解决方案。通过深入解析用户目录结构,指导用户利用符号链接和Robocopy工具,将AppData、下载文档等占用大户迁移至其他分区,并附带了自动化脚本,从根本上实现C盘瘦身,同时确保系统稳定和数据安全。

weixin_29231221的博客 2087

【数据结构与算法分析】0基础带你学数据结构与算法分析06--树(TREE)

Tree 是一些结点的集合,这个集合可以是空集;若不是空集,则 Tree 是由称为根的结点 r 以及零或多个非空的子树 T1,T2,⋯ ,​ 组成,这些子树的根都与 r 有一条有向边 (edge) 连接。这些子树的根被称为根 r 的孩子 (child),而 r 是这些 child 的父亲 (parent)。

感谢您的关注! 932

解决创建conda环境时Solving environment: failed 和 ResolvePackageNotFound 的错误

环境配置文件是在别的机器上导出的,文件里的软件包是按照导出文件的机器配置的,因此导出的时候,把这些包的详细信息也导了出来,即第二个等号后面跟着的信息,当我们按照这个文件创建环境时,conda就会根据我们机器的配置信息,按照配置文件里包的详细信息,去找这个包,那当然找不到,结果发现“查无此包”,因此也就会报上面的错误。上面找到了问题的所在之处,解决起来就很简单了,只需要在配置文件 environment.yml 中将包的详细信息删除,也就是第二个等号后面的内容。然而升级超级慢不说,也没有解决我的问题。...

番茄炒蛋三分糖 4万+

【树论】最近公共祖先(LCA)

LCA(最近公共祖先)用于求树中两节点的 deepest 共同祖先。常用倍增法,预处理 O(n log n),查询 O(log n),核心是二进制跳跃与深度调整。

zhangmohan123321的博客 1522

C++游戏开发入门:从环境配置到第一个完整项目

C++ 作为游戏开发领域的关键语言,其学习路径常因语法枯燥而令初学者却步。以项目驱动的方式学编程,能帮助学习者将变量、循环、函数、指针等基础概念融入实际游戏逻辑中,获得即时反馈与完整项目经验。掌握合适的开发环境是高效实践的前提,例如在 Windows 下使用 VS Code 搭配 MinGW-w64 编译器,配合调试器与构建脚本,即可搭建轻量可扩展的 C++ 游戏开发工作流。此类课程通常面向无基础人群,从控制台小游戏逐步过渡到带游戏循环的完整作品,过程中还需关注性能观察、素材授权与版本管理。无论你是刚接触编

weixin_30621959的博客 541

逆向分析第一步:如何从HEX文件‘还原’出单片机的原始程序与数据?

本文详细解析了如何从HEX文件逆向分析出单片机的原始程序与数据,涵盖了固件逆向的底层逻辑与实践。通过介绍HEX文件的结构、内存映像重建技术以及专业工具链的使用,帮助读者掌握从十六进制数据到可执行代码的完整流程,适用于嵌入式系统开发和逆向工程领域。

weixin_29745609的博客 317

LCA算法以及原理详解

LCA-最近公共祖先   LCA(Least Common Ancestors),即最近公共祖先,这种描述是基于树结构的,也即我们通通常只在树结构中考虑祖先问题。树实际上就是图论中的有向无环图,而要研究LCA问题,首先我们要指定树中的一个顶点为根节点,并以该节点遍历有向无环图,生成一颗DFS序下的有向树,假设我们要查询的两个节点为u,v,DFS序下根节点到两点的最短路径分别是(r,u),和(r,v),LCA就是(r,u)与(r,v)公共路径的最后一个节点,如下图所示,w即为LCA。   换句话说,u,v的

qq_37957064的博客 2万+

Python 实战:全面解析“微信搜一搜”内容爬取,从入门到企业级架构

本文将带你从零搭建爬虫项目,采用 Requests、Scrapy、Selenium、Proxy 池、中间人监控(如 Fiddler/mitmproxy)、分布式调度、数据库持久化、断点续抓等方案,实现可持续、抗封能力强的内容抓取系统。理解“微信搜一搜”页面结构与 Javascript 渲染逻辑;使用 Scrapy 框架搭建分布式爬虫;使用 Selenium 模拟浏览器抓取;构建代理池提升爬取成功率;对抗验证码、IP 封禁与 cookie 过期问题;

2201_76125261的博客 1393

LCA的求法和扩展

LCA的求法和扩展求解树上LCA(最近公共祖先)11,朴素dfs(形象的说就是:爬!)22,在线:倍增跃迁33,tarjan:离线使用LCA最长树边的长度 求解树上LCA(最近公共祖先) 先上个友链:来自队长的极佳blog 11,朴素dfs(形象的说就是:爬!) 思路: 从两个点开始,先把深度更深的节点爬到两个节点相同的地步 两个节点一起上移,直到同一深度 过于直白,过程略 22,在线:倍增跃迁 规定:dep[0]=0dep[0]=0dep[0]=0(哨兵),默认lca第一个参的dep[x]dep[x]

qq_42852687的博客 348

Yolov8损失函数改进:MPDIoU新型边界框相似度度量,效果秒杀GIoU 、 DIoU 、CIoU 、 EIoU等 | ELSEVIER 2023

ELSEVIER 2023 MPDIoU新型边界框相似度度量助力yolov8,适用提升小目标、遮挡物性能提升

①答疑群聊服务;②YOLO大模型知识问答系统;③计算机视觉论文生成智能体; 7775

PyTorch实战(26)——PyTorch分布式训练

在本节中,我们将探讨如何通过跨机器和机器内多进程的分布式训练来加速模型训练过程。我们将系统学习 PyTorch 提供的三大分布式训练 API——torch.distributed、torch.multiprocessing 以及 torch.utils.data.distributed.DistributedSampler,使用这些 API 能够极大的简化分布式训练,介绍如何使用 PyTorch 的分布式训练工具,在 CPU 和 GPU 上加速训练。

盼小辉丶的博客 3824

Tree[LCA模板]

LCA求公共祖先

Young_Zn_Cu 194

RK3568/RK3588 + YT 9215交换机芯片,MAC TO MAC 调试记录

原来的方案是rk3568 gmac 直接接phy,phy 接 switch 芯片,只是把交换芯片当交换用,驱动方面基本不用开发,但是要做vlan 那么必须涉及交换芯片的开发。选择裕太微有两个方面的原因:1.国产化替代2.可获得原厂技术支持3.目前已经完成 两个gmac 口交换芯片的配置,实现vlan,内部交换,两个光口可正常通信。

Nyiragongo的博客 1万+

vue中使用antv G6 的树图TreeGraph (紧凑树)①【新手学习向记录】

在vue中使用antv G6 树图,根据数据数值自定义节点。

yuryS的博客 9211

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

深度学习工具包 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")

Tree——LCA

题目描述: 题目背景: SOURCE:NOIP2015-SHY 给出一棵带有边权的树,问两点之间的距离。 输入格式: 第一行两个整数 n 和 m ,分别表示点数和询问数。 接下来 n-1 行,每行三个整数 x,y,z,表示 x 与 y 通过一条权为 z 的边连接。 接下来 m 行,每行两个整数 x,y,代表一组询问。 输出格式: 输出 m 行,每行一个整数,对应一组询问的答案。 样

千古的博客 314

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

最近公共祖先LCA问题

问题描述 求有根树的任意两个节点的最近公共祖先。 分析与解法 解答这个问题之前,咱们得先搞清楚到底什么是最近公共祖先。最近公共祖先简称LCA(Lowest Common Ancestor),所谓LCA,是当给定一个有根树T时,对于任意两个结点u、v,找到一个离根最远的结点x,使得x同时是u和v的祖先,x 便是u、v的最近公共祖先。(参见:http://en.wikipedia.o

Al_xin的专栏 2570

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

Leetcode 1483. Kth Ancestor of a Tree Node [Python]

这题这么理解,节点的数量不大于 50000, 按照最差情况下,这个tree是BST来做高度计算,当高度为16时,我们有2**16(= 65536 > 50000)个节点, 所以从root向下走,最多走15步到达最远的子节点,所以我们用全局常量self.step = 15来确定我们树的高度。同时我们计算2**step的距离下,各个节点的2**step距离的父节点,并存入self.parentlist中,则我们得到parentlist中的每个元素为一个字典,字典的index代表如果求某个节点的2**ind

sinat_30403031的博客 192

[复习]LCA Tree

题目背景 SOURCE:NOIP2015-SHY题目描述 给出一棵带有边权的树,问两点之间的距离。输入格式 第一行两个整数 n 和 m ,分别表示点数和询问数。 接下来 n-1 行,每行三个整数 x,y,z,表示 x 与 y 通过一条权为 z 的边连接。 接下来 m 行,每行两个整数 x,y,代表一组询问。输出格式 输出 m 行,每行一个整数,对应一组询问的答案。样例数据 输入 3

g19zwk的博客 322

Leetcode 1483. Kth Ancestor of a Tree Node 二进制思想or分布式思想

思想 如果每个结点,都保存了它所有的祖先结点,最终时间复杂度或者空间复杂度都会爆,导致无法通过测试样例 因此,想办法把O(n)O(n)O(n)变成O(log⁡n)O(\log n)O(logn)就能做出来了 让每个结点只保存一部分祖先,然后通过互相之间的关系,从而得到全部的信息 即,让每个结点保存它的第1,2,4,8…个祖先 代码 class TreeAncestor { public: vector<vector<int> > P; // P[i][node] ::::

Xurui_Luo的博客 387

树---求二叉搜索树中两节点的最低公共祖先(LCA)

一、问题描述给定二叉搜索树(BST)中两节点,找出他们的最低公共祖先。例如对于下图: LCA(4, 14)=8; LCA(8, 10)=8.二、问题求解利用BST的性质,从根节点从上自下递归遍历BST。假设n1,n2都在BST中,并且n1 < n2。 (1)在遍历过程中,遇到的第一个值介于n1和n2之间的节点n,也即n1 =< n <= n2, 就是n1和n2的LCA。 (2)在遍历过程中,如

爱橙子的OK绷的专栏 1705

Tree(可持久化字典树 树上区间 LCA)

original link - http://acm.hdu.edu.cn/showproblem.php?pid=4757 题意: 给出一棵点权树,每个查询要求出两个点之间的路径上的一个点,与给出的值异或最大。 解析: 区间单点异或===字典树 维护一个可持久化字典树,那么(x,y)(x,y)(x,y)分解为(x,lca)+(lca,y)(x,lca)+(lca,y)(x,lca)+(lca,y...

QAQ 521

Hard 单词变型成另一个单词 @CareerCup

对起始单词的每一个字母都做替换,把替换后的单词加入到queue中,并同时维护一个Map来记录变化前单词和变化后单词的联系。用来回溯时能打印出路径。 package Hard; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.Queue; impor

4761

Hard 找到由其它单词组成的最长单词 @CareerCup

用DFS的那个模板就能做出来,值得注意的是一个词必须被除自己外的其他词组成才行,不能是自己组成自己。 package Hard; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import CtCILibrary.A

3649

Tree_Graph 判断T2是否为T1的子树 @CareerCup

原文: You have two very large binary trees: T1, with millions of nodes, and T2, with hundreds of nodes. Create an algorithm to decide if T2 is a subtree of T1 译文: 有两棵很大的二叉树:T1有上百万个结点,T2有上百个结点。写

3487

Stack_Queue 把栈排序 Sort a stack @CareerCup

原文: Write a program to sort a stack in ascending order. You should not make any assumptions about how the stack is implemented. The following are the only functions that should be used to write thi

3231

Stack_Queue 猫狗队列问题 Cat dog queue @CareerCup

An animal shelter holds only dogs and cats, and operates ona strictly “first in, first out” basis. People must adopt either the “oldest”(based on arrival time) of all animals at the shelter, or they

3092
上一篇: Tree_Graph Inorder Successor in Binary Search Tree BST中找中序遍历的后继节点 @CareerCup
下一篇: Tree_Graph 判断T2是否为T1的子树 @CareerCup
chiiis
博客等级 码龄14年 422粉丝 429原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值