LeetCode 1110. Delete Nodes And Return Forest (二叉树构建非常好的题目!)

准静态电磁场 叠加法 缺点:对于连续分布的电荷,叠加法的计算比较困难 虚位移法 概念 广义坐标:确实系统中导体形状、尺寸与位置的一组独立几何量。 广义力:企图改变某一广义坐标的力。 功:广义力乘上由它引起的广义坐标的改变量。 公式 ... 阅读详情
  1. Delete Nodes And Return Forest
    Medium

Given the root of a binary tree, each node in the tree has a distinct value.

After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees).

Return the roots of the trees in the remaining forest. You may return the result in any order.

Example 1:

Input: root = [1,2,3,4,5,6,7], to_delete = [3,5]
Output: [[1,2,null,4],[6],[7]]
Example 2:

Input: root = [1,2,4,null,3], to_delete = [3]
Output: [[1,2,4]]

Constraints:

The number of nodes in the given tree is at most 1000.
Each node has a distinct value between 1 and 1000.
to_delete.length <= 1000
to_delete contains distinct values between 1 and 1000.

解法1:
个人感觉这是一道非常好的关于二叉树的构建的题目。
这题我感觉挺难的。我是参考的labuladong的做法。

  1. 只有当没有parent并且不被删除,就是res中一个新的TreeNode *
  2. 如果一个节点被删除了,我们不能直接返回NULL,因为还要处理其子节点。其子节点的hasParent都是false。
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<TreeNode*> delNodes(TreeNode* root, vector<int>& to_delete) {
        for (auto del : to_delete) {
            us.insert(del);
        }
        helper(root, false);
        return res;
    }
private:
    unordered_set<int> us;
    vector<TreeNode *> res;
    
    TreeNode * helper(TreeNode *root, bool hasParent) {
        if (!root) return NULL;
        bool toDelete = (us.find(root->val) != us.end());

        //没有parent并且不被删除,就是res中一个新的TreeNode *
        if (!toDelete && !hasParent) {
            res.push_back(root);
        }
        //if toDelete, the children's hasParent = false;
        root->left = helper(root->left, !toDelete);
        root->right = helper(root->right, !toDelete);
        return toDelete ? NULL : root;
    }
};
解决:请求的资源[/xxx/]不可用 描述 源服务器未能找到目标资源的表示或者是不愿公开一个已经存在的资源表示。 解决:请求的资源[/xxx/]不可用 描述 源服务器未能找到目标资源的表示或者是不愿公开一个已经存在的资源表示。 阅读详情

相关推荐

《点亮创新灯塔!AI应用架构师与中小学初等教育AI智能体,共筑智能化教育辅助创新灯塔》

中小学AI智能体,是基于AI技术,能感知教育场景、理解教育规律、辅助教师教学和学生学习的智能系统。做老师“做不了”的事:比如5分钟批改45本作业,精准统计每个学生的易错点;做老师“做不好”的事:比如根据学生的学习风格(视觉/听觉/动觉)推荐个性化内容;绝不做老师“该做的事”:比如情感交流、价值观引导、创意教学设计——这些“人的温度”,AI永远无法替代。我是林宇,资深AI应用架构师,专注教育AI领域8年,参与过10多个中小学AI智能体项目,曾为北京、上海、深圳等城市的100多所学校提供AI教育解决方案。

Java大师兄的博客 433

leetcode 1110. Delete Nodes And Return Forest 删点成林(中等)

二叉树的题首先想到用递归,递归方法传递4个参数,当前节点;是否是根节点(如果是根节点、且存在左右子树才会形成新树);再传递一个hashset用来存储要删除的节点,达到常数据级搜索;还有一个保存结果的list。

ln_ydc的专栏 382

【IPAM】Netbox docker模式版本升级

NETBOX 是一个开源的网络资源管理系统,主要用于管理 IP 地址、机架、设备、接口等网络资源信息。下面是 NETBOX 的功能、优点和缺点的详细介绍。

u012153104的博客 1329

Leetcode 1110.删点成林(Delete Nodes And Return Forest)

Leetcode 1110.删点成林 1 题目描述(Leetcode题目链接)   给出二叉树的根节点 root,树上每个节点都有一个不同的值。 如果节点值在 to_delete 中出现,我们就把该节点从树上删去,最后得到一个森林(一些不相交的树构成的集合)。 返回森林中的每棵树。你可以按任意顺序组织答案。 输入:root = [1,2,3,4,5,6,7], to_delete = [3,5] 输出:[[1,2,null,4],[6],[7]] 提示: 树中的节点数最大为 1000。 每个节点都有一

qq_39378221的博客 370

倍福Beckhoff运动控制功能块实战解析:从MC_ReadActualPosition到MC_GearInVelo

本文深入解析倍福(Beckhoff)TwinCAT运动控制功能块,从基础的MC_ReadActualPosition、MC_Power等轴状态读取与使能操作,到MC_MoveAbsolute、MC_MoveRelative等单轴定位指令,并重点剖析了用于动态速度同步的核心功能块MC_GearInVelo在飞锯等场景的应用。文章结合实战经验,详细介绍了齿轮耦合、电子凸轮(MC_CamIn)等高级同步功能的参数配置、调试技巧及常见问题,旨在帮助工程师快速掌握倍福运动控制工具箱,实现复杂的同步工艺。

transformer2023的博客 981

大厂嵌入式面试常考八股文及算法

1.指向已被释放或无效的内存地址的指针是野指针。互斥锁是一种用于线程同步的机制,用于确保同一时间只有一个线程访问共享资源。多态是面向对象编程中的一种特性,它允许以一种统一的方式处理不同类型的对象,通过相同的接口可以表现出不同的行为。大小端(Endian)指的是在计算机存储和处理多字节数据时,字节的存储顺序。大端序(Big Endian):高位字节存储在低地址,低位字节存储在高地址。类似于将数字的高位放在左边,低位放在右边的表示方式。例如整数值0x12345678在内存中按照大端序排列为。

谢谢大家的关注 6153

1110. Delete Nodes And Return Forest

题目: 给定一棵二叉树,和一个数组。删除树中值等于数组元素值的节点。用queue来保存所有节点。

qing2019的博客 416

Altium Designer(AD24/25)PCB编辑的几种方法介绍

本文介绍了Altium Designer(AD24/25)软件中PCB编辑的四种操作方法:1)通过菜单栏"Place→Component"激活;2)点击工具栏元器件图标;3)右键快捷菜单选择;4)快捷键P+C组合操作。建议初学者先通过菜单栏和快捷菜单熟悉操作,熟练后转为工具栏和快捷键以提高效率。文章配有操作示意图,帮助用户快速掌握PCB元器件放置技巧。

fydar的博客 937

Leetcode-1110. Delete Nodes and Return Forest

Original Link: https://leetcode.com/problems/delete-nodes-and-return-forest/ First, consider a similar but replacing trees to linked node question, There are two kinds of nodes: To be deleted (D) and ...

Liuu Zn的博客 364

基于AOD-Net与GAN的深度学习去雾算法开发

本文提出一种结合AOD-Net与GAN的深度学习去雾算法。通过改进的AOD-GAN网络架构,集成风格迁移模块,设计包含对抗损失、内容损失和风格损失的复合目标函数。实验表明,该方法在PSNR(24.67)、SSIM(0.92)和FID(32.15)指标上优于传统方法,实现了端到端的物理模型引导图像去雾。未来将优化多尺度特征融合和轻量化部署。

huanghm88的专栏 593

关务管理项目专题:SAP 与关衡关务系统的进出口报关业务集成(1)需求和方案整理

一个拥有进出口业务的企业就需要报关,而关务系统就是用来辅助企业日常进出口报关,同时数字化、合规化报关业务的有效工具。本章属于关务管理项目专题系列,以 SAP 与关衡关务系统的进出口报关业务集成为实例,详细讲解报关业务的需求和方案整理。

SAP李斌,本人承诺所有原创文章均不使用任何AI生成技术,请大家放心阅读。 2075

【LeetCode】1110. Delete Nodes And Return Forest 解题报告 (C++)

作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录题目描述题目大意解题方法递归日期 题目地址:https://leetcode.com/problems/delete-nodes-and-return-forest/ 题目描述 Given the root of a binary tree, each node ...

负雪明烛 1550

构网型逆变器下垂控制与电流限幅策略研究:理论、仿真与代码实现

随着分布式发电和微电网技术的快速发展,构网型(Grid-Forming, GFM)逆变器因其能够自主建立电压和频率参考、支撑弱电网及孤岛运行而受到广泛关注。本文提出并实现了一种基于下垂控制的构网型逆变器控制策略,将逆变器等效为受控电压源,通过L型滤波器接入配电网。在公共耦合点(PCC)处实时测量三相电压和电流,计算有功和无功功率,进而采用P-w和Q-V下垂控制生成内部频率和电压幅值,合成三相参考电压。针对故障情况下过电流问题,设计了一种自适应电流限幅模块:当电流幅值超过设定上限时,动态降低电压参考系数k_s

huanghm88的专栏 153

LeetCode-1110. Delete Nodes And Return Forest [C++][Java]

Given therootof a binary tree, each node in the tree has a distinct value. After deleting all nodes with a value into_delete, we are left with a forest (a disjoint union of trees). Return the roots of the trees in the remaining forest.

贫道绝缘子的博客 281

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

[leetcode] 1110. Delete Nodes And Return Forest

Description Given the root of a binary tree, each node in the tree has a distinct value. After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees). Return the roots of the trees in the remaining forest. You

Learning from the mistakes 339

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

LeetCode #1110. Delete Nodes And Return Forest

题目描述: Given therootof a binary tree, each node in the tree has a distinct value. After deletingall nodes with a value into_delete, we are left with a forest (adisjoint union of trees). Return ...

LawFile的博客 289

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

LeetCode 1110 Delete Nodes And Return Forest (DFS 推荐)

Given therootof a binary tree, each node in the tree has a distinct value. After deletingall nodes with a value into_delete, we are left with a forest (adisjoint union of trees). Return the roo...

Tc的专栏 276

LeetCode in Python 1110. Delete Nodes And Return Forest

Given therootof a binary tree, each node in the tree has a distinct value. After deletingall nodes with a value into_delete, we are left with a forest (adisjoint union of trees). Return th...

weixin_30305735的博客 268

LeetCode 1110. Delete Nodes And Return Forest【二叉树,DFS,哈希表】中等

本文属于「征服LeetCode」系列文章之一,这一系列正式开始于2021/08/12。由于LeetCode上部分题目有锁,本系列将至少持续到刷完所有无锁题之日为止;由于LeetCode还在不断地创建新题,本系列的终止日期可能是永远。在这一系列刷题文章中,我不仅会讲解多种解题思路及其优化,还会用多种编程语言实现题解,涉及到通用解法时更将归纳总结出相应的算法模板。。

memcpy0的博客 990

LeetCode 1110. Delete Nodes And Return Forest

Given therootof a binary tree, each node in the tree has a distinct value. After deletingall nodes with a value into_delete, we are left with a forest (adisjoint union of trees). Return the roots of the trees in the remaining forest. You may return...

taoqick的专栏 303

Leetcode 1110 Delete Nodes And Return Forest + Leetcode 897 Increasing Order Search Tree

首先这道题需要分解,如果我的函数定义为删除节点并且一个forest的list,然后左子树右子树,很显然做不出来。对于这道题而言然后这个函数还有一个任务,然后判断什么时候我需要把值collect起来:当root节点的爸爸是个nullptr或者当root节点的爸爸要被删除的时候要收集root,结束。题意:根据一个list删除节点并且返回删除,节点的头,如果头是需要删除的,那就不返回。不然的话你每一层树的结构都没有改变,根节点还是指向的是先前的节点,这个就不对了。在树的形态并没有发生改变的时候,后序遍历。

xxxmmc的博客 277

LeetCode 1110. Delete Nodes And Return Forest(java)

Given the root of a binary tree, each node in the tree has a distinct value. After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees). Return the roots...

katrina95的博客 590

LeetCode //C - 1110. Delete Nodes And Return Forest

This problem involves deleting specified nodes from a binary tree and returning the remaining forest (disjoint trees). The solution uses post-order DFS traversal to process nodes. If a node is marked for deletion, its non-deleted children become new roots

Made in Code 201

LeetCode学习笔记(4) 第1110题 Delete Nodes And Return Forest

文章目录题目分析流程代码知识点 题目 分析 解决tree的问题, 一般考虑使用递归,根据不同的题目,可以选择不同的遍历方式(前序,中序,后序遍历),本题可以使用后序遍历,最后处理根节点, 先分别处理每个节点的左子树,右子树 流程 使用后序遍历,观察每一个节点是否需要被删除,如果需要删除,保存该节点的左右子树(如果存在的话),不需要删除直接返回。 代码 python # Definition for a binary tree node. # class TreeNode(object): # de

weixin_39278430的博客 449

【leetcode】1110. Delete Nodes And Return Forest

题目如下: Given therootof a binary tree, each node in the tree has a distinct value. After deletingall nodes with a value into_delete, we are left with a forest (adisjoint union of trees). ...

weixin_30254435的博客 119

【Leetcode】1110. Delete Nodes And Return Forest

中数字的节点删掉,另一个是要将删完了之后产生的森林的树根加入列表中。删除节点的方法就是,在DFS的时候返回当前节点的子树做删除操作完成之后的树根,所以也就是说,如果当前节点就是要删的,则返回null,否则返回当前节点自己。而收集森林树根的过程必须先于返回节点执行,也就是这里应该是要后序遍历。我们需要在DFS的时候再传一个参数,即当前节点是否是森林的树根。否则的话,要么其没有父亲,要么其父亲会被删,这两种情况下当前节点会成为森林的某个树根,从而要加入答案。中存在的节点删掉,并返回得到的森林的每棵树的树根。

数学、算法爱好者的博客 273
上一篇: Leetcode 998. Maximum Binary Tree II (二叉树构建好题)
下一篇: LintCode 3690 Clone Binary Tree II (二叉树构建好题)
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值