814. 二叉树剪枝
题目描述
解题思路
1、树的剪枝
代码实现
# 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: TreeNode) -> TreeNode:
# pruneTrue(root)返回剪枝后的树
if not root:
return
root.left = self.pruneTree(root.left) # 左子树剪枝,得到剪枝后左子树
root.right = self.pruneTree(root.right) # 右子树剪枝,得到剪枝后右子树
# 判断决定root结点是否需要剪掉
if not root.left and not root.right and int(root.val) == 0:
return
# 返回root这棵树剪枝后的结果
return root