当前位置:网站首页>【LeetCode】814. 二叉树剪枝
【LeetCode】814. 二叉树剪枝
2022-07-22 05:56:00 【pass night】
题目
难度中等293收藏分享切换为英文接收动态反馈
给你二叉树的根结点 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
思路
- 递归所有结点
- 若当前结点为0且为叶子结点,则删除当前结点
代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root is None:
return None
root.left = self.pruneTree(root.left)
root.right = self.pruneTree(root.right)
if root.left is None and root.right is None and root.val == 0:
return None
return root
复杂度
- 时间复杂度:O(n)
- 空间复杂度:O(n)
边栏推荐
- Cross domain problem (CORS) detailed description and solution
- Detailed explanation of wechat payment project practice, order creation to payment refund code
- Web3流量聚合平台Starfish OS,给玩家元宇宙新范式体验
- Tutorial update 20220719
- Blob URL DataURL
- @The difference between resource and @autowired
- Ffmpeg-rk3399 ffplay learning analysis
- Enthusiasm and expertise fly together | Microsoft's most valuable expert project, attracting Microsoft technology contributors!
- July 19, 2022 daily
- NFS网络文件系统
猜你喜欢
随机推荐
NFS网络文件系统
Make good use of these seven tips in code review, and it is easy to establish your opposition alliance
Server network performance tuning tool
Polygon chain matic concept and underlying mechanism
Zen administrator forgets password and retrieves password
UE4 面试基础知识(三)
Blob URL DataURL
Spark高级特性,220720,
Under fitting and over fitting (regularization)
Matlab function: filtfilter -- zero phase digital filtering
从0到1建设智能灰度数据体系:以vivo游戏中心为例
How much do you know about hande digital platform system and trial?
接招吧。最强“高并发”系统设计 46 连问,分分钟秒杀一众面试者
-bash-4.2$
服务器网络性能调优案例
In the arm64 environment, the third-party library hajimehoshi/oto of golang relies on the solution of alsa lib and CGO
Can0 transceiver + receive interrupt configuration and baud rate calculation of gd32f470 (detailed)
15_ Additional models
牛客网 替换空格
Are you still writing code for adding, deleting, modifying and checking? Direct one click generation