当前位置:网站首页>Leetcode 刷题日记 剑指 Offer II 047. 二叉树剪枝
Leetcode 刷题日记 剑指 Offer II 047. 二叉树剪枝
2022-07-28 05:26:00 【JETECHO】
原题链接(https://leetcode.cn/problems/pOCWxh/)
题目描述
给定一个二叉树 根节点 root ,树的每个节点的值要么是 0,要么是 1。请剪除该二叉树中所有节点的值为 0 的子树。节点 node 的子树为 node 本身,以及所有 node 的后代。
示例1

示例2

示例3

数据限制
- 二叉树的节点个数的范围为[1,200]
- 二叉树节点的值只能是0或1
思路
对于叶子节点只要他是0的话那么这么节点就要删除毕竟叶子节点没有子节点,删除之后如果它没有兄弟节点那么他的父节点就是叶子节点,那么又要去判断它的值是否为0,如果为0那么就需要删除掉这个节点,如果它父节点又会重蹈覆辙则还需要继续删除。从这个流程不难看出,这题的关注点是叶子节点的删除以及父节点的更迭。所以可以采用递归的方法,从叶子节点开始处理,并且回溯的时候同步处理它的父节点。最后得到最终的处理完的二叉树。
如示例2的流程就应该是




代码
public TreeNode pruneTree(TreeNode root) {
if(root==null)
return null;
root.left=pruneTree(root.left);
root.right=pruneTree(root.right);
if(root.val==0&&root.left==null&&root.right==null) {
return null;
}
return root;
}
边栏推荐
- 2022-05-15 基于jwt令牌token
- Filter
- 【学习笔记】链表操作
- Pytorch learning note 4 - automatic calculation of gradient descent autograd
- Word自动目录字体修改和行间距的问题
- Measure computer battery capacity
- Pytorch learning notes 1 - quick start
- Pytorch learning notes 3 - datasets & dataloaders & transforms
- qt中Qthread线程的使用以及安全关闭
- 夹子套利/搬砖套利系统开发
猜你喜欢

MFC 使用控制台打印程序信息

Treasure plan TPC system development DAPP construction

Several methods of QT setting loading interface

Explain the installation of MSDN 2015 and precautions

Problems of font modification and line spacing in word automatic directory

气传导蓝牙耳机哪个好、气传导蓝牙耳机排行榜

How many columns are the most suitable for Clickhouse to build a width table?

IP地址的五大分类

藏宝计划TPC系统开发Dapp搭建

C语言memcpy库函数与memmove的作用
随机推荐
相对路径和绝对路径
Listener
Listener
解决内存占用比应用进程占用高的问题
set_ multicycle_ path
C语言memcpy库函数与memmove的作用
Pytorch learning notes 2 - about tensor
IP地址的五大分类
What's a gift for girls on Chinese Valentine's day? Selfie online and thoughtful gift recommendation
execjs 调用
What's a good gift for your girlfriend on the Chinese Valentine's day in 2022? Practical and beautiful gift recommendation
Getting started with hugging face
[c语言]--一步一步实现扫雷小游戏
小程序自定义组件-数据,方法和属性
开放式耳机有哪些、四款音质超好的气传导耳机推荐
2022-06-07 六.日志实现
【学习笔记】知识管理
Find the network address and broadcast address of the host according to the IP address and subnet mask
Vscode中,无法打开源文件 “Adafruit_GFX.h“
2022年七夕礼物推荐!好看便宜又实用的礼物推荐