【树-中等】652. 寻找重复的子树

652. 寻找重复的子树 通过树的序列化和哈希表,我们能够在保证时间复杂度为O(N)的情况下,解决重复子树的问题。这个解法不仅高效,而且实现简洁,非常适合处理二叉树相关的各种问题。希望本文对你理解和实现该问题有所帮助! 阅读详情

【题目】
给定一棵二叉树,返回所有重复的子树。对于同一类的重复子树,你只需要返回其中任意一棵的根结点即可。

两棵树重复是指它们具有相同的结构以及相同的结点值。

示例 1:

    1
   / \
  2   3
 /   / \
4   2   4
   /
  4

下面是两个重复的子树:

  2
 /
4

和

4

因此,你需要以列表的形式返回上述重复子树的根结点。
【代码】

class Solution(object):
    def findDuplicateSubtrees(self, root):
        count = collections.Counter()
        ans = []
        def collect(node):
            if not node: return "#"
            serial = "{},{},{}".format(node.val, collect(node.left), collect(node.right))
            count[serial] += 1
            if count[serial] == 2:
                ans.append(node)
            return serial

        collect(root)
        return ans
leetcode — 652. 寻找重复的子树 给定一棵二叉树,返回所有重复的子树。对于同一类的重复子树,你只需要返回其中任意一棵的根结点即可。 两棵树重复是指它们具有相同的结构以及相同的结点值。 示例 1: 1 / \ 2 3 / / \ 4 2 4 / 4 下面是两个重复的子树: 2 / 4 和 4 因此,你需要以列表的形式返回上述重复子树的根结点。 题目给出了一棵二叉树 返回树中 阅读详情

相关推荐

别再硬啃C代码了!用Simulink的Matlab Function模块手把手教你搭建CRC8校验模型(附完整M脚本)

本文详细介绍了如何利用Simulink的Matlab Function模块轻松实现CRC8校验模型,替代传统的C代码编写。通过可视化建模和即时验证,开发者可以高效完成算法设计,并自动生成嵌入式代码。文章包含完整的M脚本示例和工程实践技巧,特别适合嵌入式系统开发人员提升工作效率。

weixin_42520661的博客 186

Java实现 LeetCode 652 寻找重复的子树(两个map的DFS)

652. 寻找重复的子树 给定一棵二叉树,返回所有重复的子树。对于同一类的重复子树,你只需要返回其中任意一棵的根结点即可。 两棵树重复是指它们具有相同的结构以及相同的结点值。 示例 1: 1 / \ 2 3 / / \ 4 2 4 / 4 下面是两个重复的子树: 2 / 4 和 4 因此,你需要以列表的形式返回上述...

南 墙 1万+

别再用UE5默认材质:用Substance Painter一招提升写实感

今天,我就把这套从模型准备到引擎最终呈现的全流程技巧毫无保留地分享出来,这套方法不仅能让你的作品细节炸裂,更能让你理解次世代PBR(Physically Based Rendering)材质的底层逻辑。

海外旅居设计师,15年设计经验。 1329

LeetCode 652:寻找重复的子树

目录LeetCode 652:寻找重复的子树题目描述解题 LeetCode 652:寻找重复的子树 题目描述 解题      /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} *

s_Shune 244

camera——HAL层知识分享

CameraHAL层是Android相机系统的核心中间层,负责连接Framework层与硬件驱动层。它通过标准化接口解耦软硬件,实现跨平台兼容性,同时为厂商提供硬件定制空间。主要功能包括:设备管理、数据流处理、参数控制以及图像优化。关键子系统涵盖预览、拍照、录像、对焦与曝光等模块,采用HAL3的"请求-响应"模型实现精细控制。性能优化重点关注启动时间、帧率稳定性和延迟控制。通过分层架构设计(接口层-核心层-适配层)和缓冲池机制,确保高效数据传输和硬件资源调度。

2302_77429403的博客 2084

Android/AutoMotive 多用户文件操作与权限管理

本文深入探讨了Android/Automotive多用户系统的文件操作与权限管理机制。文章阐述了多用户隔离与共享的核心原理,重点介绍了如何使用adb指令精准管理不同用户的应用与数据,并提供了在Android Automotive车载场景下实现安全跨用户数据共享与权限控制的最佳实践。

weixin_29214691的博客 164

【leetcode-652】寻找重复的子树

【leetcode-652】寻找重复的子树 题目描述 给定一棵二叉树,返回所有重复的子树。对于同一类的重复子树,你只需要返回其中任意一棵的根结点即可。 两棵树重复是指它们具有相同的结构以及相同的结点值。 题解 /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {}

JasonLee实时计算 5353

晶圆表面缺陷检测现状概述

凹坑,凸起,尖角,沟槽),使用光束对晶圆进行照射,收集反射光和散射光信息进行缺陷判断,进一步可分为无图案晶圆表面检测和宏观缺陷检测设备。KLA使用SR-DUV光,检测精度在10nm以下。扫描电子显微(电子束和晶圆表面产生二次电子,X射线等)获取高分辨率的图像,然后用图像处理表面缺陷(凹坑,凸起,尖角,沟槽等)表面容貌和材料信息,分辨率可达5-10nm。晶圆表面缺陷检测设备主要检测晶圆外观呈现出来的缺陷,损伤、毛刺等缺陷,主要设备供应商KLA,AMAT,日立等,其中KLA在晶圆表面检测设备占有市场52%左右。

qq_36786800的博客 1万+

Leetcode 652. 寻找重复的子树 C++

Leetcode 652. 寻找重复的子树 题目 给定一棵二叉树,返回所有重复的子树。对于同一类的重复子树,你只需要返回其中任意一棵的根结点即可。 两棵树重复是指它们具有相同的结构以及相同的结点值。 示例: 1 / \ 2 3 / / \ 4 2 4 / 4 下面是两个重复的子树: 2 / 4 和 4 因此,你需要以列表的形式返回上述重复子树的根结点。 题解 后序

weixin_43750513的博客 603

C# 与欧姆龙 PLC 实战:通过 Ethernet/IP 协议进行设备控制与监控

本文介绍了如何通过C#和Ethernet/IP协议实现与欧姆龙PLC的通信。Ethernet/IP是基于以太网的工业协议,适用于工业设备间的实时数据交换。文章详细讲解了使用EthernetIPSharp库建立连接、读写数据的步骤,并提供了示例代码。此外,还探讨了实时监控、报警系统等高级功能,为工业自动化控制系统开发提供了实用指导。该方法简化了PLC通信开发,提高了系统可靠性和智能化程度。

这里只有干货:从 Modbus 通信到 MES 对接,从 YOLO 训练到工控机部署,带你搞定工业软件开发全流程。 817

新手福利!大龙虾OpenClaw可视化管理工具来了!告别命令行,这个可视化工具让OpenClaw管理变得超简单

还在用命令行管理OpenClaw?🚀 这个跨平台可视化工具支持14+AI模型,一键切换,还能对接微信飞书钉钉等8大消息渠道,让AI助手管理变得简单直观 ✅ 暗色主题护眼舒适,Rust后端高性能低占用,新手也能轻松上手 🎯

XiaoqiangClub的博客 765

寻找重复的子树

题目介绍 力扣652题:https://leetcode-cn.com/problems/find-duplicate-subtrees/ 给定一棵二叉树,返回所有重复的子树。对于同一类的重复子树,你只需要返回其中任意一棵的根结点即可。 两棵树重复是指它们具有相同的结构以及相同的结点值。 分析 函数签名如下: List findDuplicateSubtrees(TreeNode root); 我来简单解释下题目,输入是一棵二叉树的根节点root,返回的是一个列表,里面装着若干个二叉树节点,这些节点对

weixin_48276298的博客 2003

Pytorch入门教程

Pytorch学习总结:1.张量Tensor 张量是一种特殊的数据结构,与数组和矩阵非常相似。在PyTorch中,我们使用张量对模型的输入和输出以及模型的参数进行编码。 张量类似于NumPy的ndarray,除了张量可以在 GPU 或其他硬件加速器上运行。事实上,张量和NumPy数组通常可以共享相同的底层内存,从而无需复制数据。...

专注大数据与人工智能技术分享,欢迎私信加群互相学习! 4万+

二叉树题目:寻找重复的子树

文章目录题目标题和出处难度题目描述要求示例数据范围解法思路和算法证明代码复杂度分析 题目 标题和出处 标题:寻找重复的子树 出处:652. 寻找重复的子树 难度 7 级 题目描述 要求 给定二叉树的根结点 root\texttt{root}root,返回所有重复的子树。 对于同一类的重复子树,只需要返回其中任意一个子树的根结点即可。 如果两个树具有相同的结构和相同的结点值,则它们是重复的。 示例 示例 1: 输入:root = [1,2,3,4,null,2,4,null,null,4

stormsunshine的博客 1685

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

LeetCode 652——寻找重复的子树

一、题目介绍 给定一棵二叉树,返回所有重复的子树。对于同一类的重复子树,你只需要返回其中任意一棵的根结点即可。 两棵树重复是指它们具有相同的结构以及相同的结点值。 示例 1: 下面是两个重复的子树: 和 4 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/find-duplicate-subtre...

Asher 498

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

leetcode652. 寻找重复的子树

leetcode652. 寻找重复的子树 给定一棵二叉树,返回所有重复的子树。对于同一类的重复子树,你只需要返回其中任意一棵的根结点即可。 两棵树重复是指它们具有相同的结构以及相同的结点值。 示例 1: 1 / \ 2 3 / / \ 4 2 4 / 4 下面是两个重复的子树: 2 / 4 和 4 因此,你需要以列表的形式返回上述重复子树的根结...

peony的博客 199

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

LeetCode——652 寻找重复的子树

问题描述: 给定一棵二叉树,返回所有重复的子树。对于同一类的重复子树,你只需要返回其中任意一棵的根结点即可。 两棵树重复是指它们具有相同的结构以及相同的结点值。 示例 1: 1 / \ 2 3 / / \ 4 2 4 / 4 下面是两个重复的子树: 2 / ...

优快云的博客 345

leetcode 652.寻找重复的子树 Java

寻找重复的子树题目链接描述示例初始代码模板代码 题目链接 https://leetcode-cn.com/problems/find-duplicate-subtrees/ 描述 给定一棵二叉树,返回所有重复的子树。对于同一类的重复子树,你只需要返回其中任意一棵的根结点即可。 两棵树重复是指它们具有相同的结构以及相同的结点值。 示例 1 / \ 2 3 / / \ 4 2 4 / 4 下面是两个重复的子

博主是个二次元死肥宅~ 528

leetcode 652. 寻找重复的子树

题目链接 https://leetcode-cn.com/problems/find-duplicate-subtrees/submissions/ 题目描述 给定一棵二叉树,返回所有重复的子树。对于同一类的重复子树,你只需要返回其中任意一棵的根结点即可。 两棵树重复是指它们具有相同的结构以及相同的结点值。 1 / ...

qq_38043440的博客 500

LeetCode刷题复盘笔记—652. 寻找重复的子树

LeetCode刷题复盘笔记—652. 寻找重复的子树,判断两个子树是否重复!本题可以借助二叉树序列化的方法——把二叉树转化成字符串,每一个子树对应一个字符串,只要判断字符串是否重复,就可以知道子树是否重复,这里可以借助哈希表来判断是否重复,而且这一道题还要求输出结果不能重复:“对于同一类的重复子树,你只需要返回其中任意 一棵 的根结点即可。”所以最终考虑使用unordered_map,记录每个字符串重复次数, 只有当键值对的值为1(当前只重复1次时)时才加入到最终的输出结果中!

Lucky_Alan_Gareth的博客 295

【leetcode】二叉树,652寻找重复的子树,236二叉树的最近公共祖先

【leetcode】652. 寻找重复的子树题目难度:中等题解一:DFS 链接:https://leetcode-cn.com/problems/find-duplicate-subtrees/ 题解: 题目难度:中等 /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNo

一个写湿的程序猿 738
上一篇: 【树-中等】103. 二叉树的锯齿形层序遍历
下一篇: 【树-中等】面试题 04.10. 检查子树
菜菜2022
博客等级 码龄9年 67粉丝 1033原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值