当前位置:网站首页>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;
}
}
边栏推荐
- How to install cpolar intranet penetration on raspberry pie
- Nacos configuration center dynamically refreshes the data source
- Lua function nested call
- 快应用JS自定义月相变化效果
- What happens if the MySQL disk is full? I really met you!
- Voice live broadcast system - Principles to be followed in developing push notifications
- Esp8266 Arduino programming example - interrupt
- 快应用自定义进度条
- It's great to write code for 32 inch curved screen display! Send another one!
- 深入浅出详解Knative云函数框架!
猜你喜欢

【武汉理工大学】考研初试复试资料分享

刷题《剑指Offer》day03

I grabbed a ticket and thought I found the system bug of 12306
![Flash memory usage and stm32subemx installation tutorial [day 3]](/img/ff/43ef2d0e1bdfd24fbc5c99e76455f1.png)
Flash memory usage and stm32subemx installation tutorial [day 3]

Voice live broadcast system - Principles to be followed in developing push notifications

Lua function nested call

ESP8266-Arduino编程实例-中断

Monitoring artifact: Prometheus easy to get started, really fragrant!

【云原生 • DevOps】一文掌握容器管理工具 Rancher

35-Spark Streaming反压机制、Spark的数据倾斜的解决和Kylin的简单介绍
随机推荐
Nacos is used as a registration center
wordpress禁止指定用户名登录或注册插件【v1.0】
July training (day 05) - double pointer
吃透Chisel语言.27.Chisel进阶之有限状态机(一)——基本有限状态机(Moore机)
35-Spark Streaming反压机制、Spark的数据倾斜的解决和Kylin的简单介绍
XML overview
Google Earth Engine APP——打印点的坐标到控制台上和map上,设置样式并更新
Understand chisel language. 24. Chisel sequential circuit (IV) -- detailed explanation of chisel memory
好久不送书,浑身不舒服
深入浅出详解Knative云函数框架!
Google Earth Engine APP——利用S2影像进行最大值影像合成分析
监控神器:Prometheus 轻松入门,真香!
食品安全 | 垃圾食品越吃越想吃?这份常见食品热量表请收好
Redis 为什么这么快?Redis 的线程模型与 Redis 多线程
刷题《剑指Offer》day04
Exercises --- quick arrangement, merging, floating point number dichotomy
GO基础知识—数组和切片
安装了HAL库如何恢复原来的版本
Quick apply custom progress bar
NPM common commands


