Leetcode 814.二叉树剪枝
1 题目描述(Leetcode题目链接)
给定二叉树根结点 root ,此外树的每个结点的值要么是 0,要么是 1。返回移除了所有不包含 1 的子树的原二叉树。( 节点 X 的子树为 X 本身,以及所有 X 的后代。)
输入: [1,0,1,0,0,0,1]
输出: [1,null,1,null,1]
2 题解
本题的意思就是如果一个节点的某个子树都是0,那就删掉这个子树,所以很容易看出递归解决这道题是非常方便的,直接看代码就可以看懂。
# 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 None
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