当前位置:网站首页>Leetcode brush questions diary sword finger offer II 047. Binary tree pruning
Leetcode brush questions diary sword finger offer II 047. Binary tree pruning
2022-07-28 06:39:00 【JETECHO】
Original link (https://leetcode.cn/problems/pOCWxh/)
List of articles
Title Description
Given a binary tree The root node root , The value of each node of the tree is either 0, Or 1. Please cut off all nodes in the binary tree. The value is 0 The subtree of . node node The subtree of is node In itself , And all node The offspring of .
Example 1

Example 2

Example 3

Data restrictions
- The number of nodes of the binary tree ranges from [1,200]
- The value of a binary tree node can only be 0 or 1
Ideas
For leaf nodes, as long as they are 0 Then the node should be deleted. After all, the leaf node has no child nodes , After deletion, if it has no sibling node, its parent node is the leaf node , Then we have to judge whether its value is 0, If 0 Then you need to delete this node , If its parent node will repeat the mistakes, it needs to continue to delete . From this process, it is not difficult to see , The focus of this problem is the deletion of leaf nodes and the replacement of parent nodes . So we can use recursive method , Start processing from the leaf node , And its parent node is processed synchronously during backtracking . Finally, get the final processed binary tree .
Such as Example 2 The process should be 




Code
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;
}
边栏推荐
- What's a gift for girls on Chinese Valentine's day? Selfie online and thoughtful gift recommendation
- What is the best and most cost-effective open headset recommended
- OJ 1020 最小的回文数
- 小程序自定义组件-数据,方法和属性
- Leetcode 刷题日记 剑指 Offer II 053. 二叉搜索树中的中序后继
- 微信小程序自定义编译模式
- Leetcode 刷题日记 剑指 Offer II 050. 向下的路径节点之和
- Icc2 use report_ Placement check floorplan
- 2021-11-10
- 【实现简易版扫雷小游戏】
猜你喜欢
随机推荐
[PTA--利用队列解决猴子选大王问题】
【C笔记】数据类型及存储
2022-07-19 Damon database connection instance, execution script, system command
Problem solving for ACM freshmen in Jiangzhong on October 26
scrapy 命令
SSAO By Computer Shader(二)
OJ 1045 reverse and add
execjs 调用
2022-06-07 ResponseBodyAdvice导致Swagger出现弹框问题
2022-05-15 based on JWT token
ZOJ Problem 1005 jugs
当前学习进度
结构体、位段、联合体(共用体)的大小如何计算
【C语言】自定义结构体类型
气传导耳机哪个品牌比较好、这四款不要错过
Get the current directory in QT
新的selenium
代码整洁之道(一)
Listener
OJ 1129 分数矩阵



![[PTA----树的遍历]](/img/d8/260317b30d624f8e518f8758706ab9.png)





