【leetcode】※814. Binary Tree Pruning

觉得自己写的很复杂,主要考验递归思想

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def pruneTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        def is_contain(root):
            if root.left==None and root.right==None:
                return False
            elif root.left==None:
                if root.right.val==1:
                    return True
                else:
                    return is_contain(root.right)
            elif root.right==None:
                if root.left.val==1:
                    return True
                else:
                    return is_contain(root.left)
            else:
                if root.left.val==1 or root.right.val==1:
                    return True
                else:
                    return is_contain(root.left)|is_contain(root.right)
        if root.left != None:
            if root.left.val==0 and is_contain(root.left)==False:
                root.left = None
            else:
                root.left = self.pruneTree(root.left)
        if root.right != None:
            if root.right.val==0 and is_contain(root.right)==False:
                root.right = None
            else:
                root.right = self.pruneTree(root.right)
        return root

36ms  do not have enough accepted submissions to show runtime distribution chart.

------------------------------------------------------

看了一下discuss,把我想的在查看递归是否含有1的时候就剪枝的功能实现了。而且判断的时候不用那么多条件判断语句。

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def pruneTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        def is_contain(root):
            if not root:     #if root is none
                return None
            a1 = is_contain(root.left)
            a2 = is_contain(root.right)
            if not a1:
                root.left = None
            if not a2:
                root.right = None
            return root.val==1 or a1 or a2
        return root if is_contain(root) else None
36ms   不过用的时间是一样的


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值