Leetcode 814. Binary Tree Pruning

dfs

要点是这一句:

return node.val==1 or node.left or node.right

完整代码:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
import functools
class Solution:
    @functools.lru_cache()
    def pruneTree(self, root: TreeNode) -> TreeNode:
        def dfs(node:TreeNode)->bool:
            if not node:
                return False
            if not dfs(node.left):
                node.left=None
            if not dfs(node.right):
                node.right=None
            return node.val==1 or node.left or node.right
        if not root:
            return
        return root if dfs(root) else None

 

posted @ 2019-04-23 03:02  周洋  阅读(169)  评论(0编辑  收藏  举报