觉得自己写的很复杂,主要考验递归思想
# 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 不过用的时间是一样的