当前位置:网站首页>LeetCode.814. 二叉树剪枝____DFS
LeetCode.814. 二叉树剪枝____DFS
2022-07-27 09:42:00 【向光.】
814. 二叉树剪枝
给你二叉树的根结点 root ,此外树的每个结点的值要么是 0 ,要么是 1 。
返回移除了所有不包含 1 的子树的原二叉树。
节点 node 的子树为 node 本身加上所有 node 的后代。
示例 1:
输入:root = [1,null,0,0,1]
输出:[1,null,0,null,1]
解释:
只有红色节点满足条件“所有不包含 1 的子树”。 右图为返回的答案。
示例 2:
输入:root = [1,0,1,0,0,0,1]
输出:[1,null,1,null,1]
示例 3:
输入:root = [1,1,0,1,1,0,1,0]
输出:[1,1,0,1,1,null,1]
提示:
- 树中节点的数目在范围 [1, 200] 内
- Node.val 为 0 或 1
Solution:
- 我们直接深搜此二叉树,当左节点右节点均为null且此节点对应val为0时,将此节点改为null即可;
Code:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */
class Solution {
public TreeNode pruneTree(TreeNode root) {
if(root.left != null)
root.left = pruneTree(root.left);
if(root.right != null)
root.right = pruneTree(root.right);
if(root.left == null && root.right == null && root.val == 0){
return null;
}
return root;
}
}
边栏推荐
- Monitoring artifact: Prometheus easy to get started, really fragrant!
- 监控神器:Prometheus 轻松入门,真香!
- 吃透Chisel语言.22.Chisel时序电路(二)——Chisel计数器(Counter)详解:计数器、定时器和脉宽调制
- Understand chisel language. 25. Advanced input signal processing of chisel (I) -- asynchronous input and de jitter
- July training (day 11) - matrix
- Nacos is used as a registration center
- 七月集训(第04天) —— 贪心
- 在Centos 7安装Mysql 5.7.27后无法启动?(语言-bash)
- MOS drive in motor controller
- Exercises --- quick arrangement, merging, floating point number dichotomy
猜你喜欢

I grabbed a ticket and thought I found the system bug of 12306

Quick apply custom progress bar

Lua function nested call

It's great to write code for 32 inch curved screen display! Send another one!

找工作 4 个月, 面试 15 家,拿到 3 个 offer

Nacos做注册中心使用

通俗易懂!图解Go协程原理及实战

NFT系统开发-教程

c'mon! Please don't ask me about ribbon's architecture principle during the interview

Explain knative cloud function framework in simple terms!
随机推荐
七月集训(第19天) —— 二叉树
July training (day 09) - two point search
I haven't delivered books for a long time, and I feel uncomfortable all over
Looking for a job for 4 months, interviewing 15 companies and getting 3 offers
通俗易懂!图解Go协程原理及实战
System parameter constant table of system architecture:
35 spark streaming backpressure mechanism, spark data skew solution and kylin's brief introduction
圆环工件毛刺(凸起)缺口(凹陷)检测案例
C # set different text watermarks for each page of word
七月集训(第03天) —— 排序
Towards the peak of life
Flash memory usage and stm32subemx installation tutorial [day 3]
监控神器:Prometheus 轻松入门,真香!
July training (day 18) - tree
注解与反射
Expose a technology boss from a poor family
给自己写一个年终总结,新年快乐!
深入浅出详解Knative云函数框架!
七月集训(第06天) —— 滑动窗口
Google Earth engine app - maximum image synthesis analysis using S2 image


