1、题目
给定二叉树根结点 root ,此外树的每个结点的值要么是 0,要么是 1。 返回移除了所有不包含 1 的子树的原二叉树。 ( 节点 X 的子树为 X 本身,以及所有 X 的后代。)
示例:
输入: [1,0,1,0,0,0,1]
输出: [1,null,1,null,1]

2、分析
此题是对二叉树进行减枝操作,只需要进行递归操作即可.
3、代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def pruneTree(self, root: TreeNode) -> TreeNode:
if not root:
return
root.left = self.pruneTree(root.left)
root.right = self.pruneTree(root.right)
if root.val == 0 and not root.left and not root.right:
return None
return root
4、结果
执行用时 :32 ms, 在所有 Python3 提交中击败了90.14% 的用户
内存消耗 :13.2 MB, 在所有 Python3 提交中击败了23.64%的用户
5、优化
。。。
望您:
“情深不寿,强极则辱,谦谦君子,温润如玉”。
来源:CSDN
作者:_23__
链接:https://blog.csdn.net/qq_40514904/article/details/103979332