814. Binary Tree Pruning
2 years ago in Python
# 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]:
def dfs(node: TreeNode) -> int:
if not node:
return 0
left = dfs(node.left)
right = dfs(node.right)
if left == 0:
node.left = None
if right == 0:
node.right = None
return left + right + node.val
dummy = TreeNode(-1, root)
dfs(dummy)
return dummy.left