814 二叉树剪枝
看到二叉树相关,用递归判断
1、判断root是否为空
2、分别判断左子树和右子树是否为空(递归)
3、找到结束条件。在本题中当左子树和右子树同时为空,且当前节点为0时,将当前节点及其后代剪掉(置为None)
# 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 not root:
return None # 1
root.left = self.pruneTree(root.left)
root.right= self.pruneTree(root.right) # 2
if root.left==None and root.right==None and root.val==0: # 3
return None
return root
以后的每日一题发布到知乎专栏