Count Univalue Subtrees
没有太好的办法,只能divide conquer然后汇总,关于空节点和单个结点树的处理非常麻烦
class Solution(object):
count = 0
def countUnivalSubtrees(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
self.helper(root)
return self.count
def helper(self, root):
if not root.left and not root.right:
self.count += 1
return (True, root.val)
left, right = True, True
leftVal, rightVal = None, None
if root.left:
left, leftVal = self.helper(root.left)
if root.right:
right, rightVal = self.helper(root.right)
if left and right:
if leftVal is None and root.val == rightVal:
self.count += 1
return (True, root.val)
if rightVal is None and root.val == leftVal:
self.count += 1
return (True, root.val)
if root.val == leftVal == rightVal:
self.count += 1
return (True, root.val)
return (False, root.val)