Question
Given a binary tree, count the number of uni-value subtrees.
A Uni-value subtree means all nodes of the subtree have the same value.
For example:
Given binary tree,
5
/ \
1 5
/ \ \
5 5 5
return 4.
Hide Tags Tree
Solution
# 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 countUnivalSubtrees(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.res = 0
if root==None:
return self.res
self.helper(root)
return self.res
def helper(self, root):
if root.left==None and root.right==None:
self.res += 1
return True
if root.left==None and root.right!=None:
r = self.helper(root.right)
if r and root.val==root.right.val:
self.res += 1
return True
else:
return False
elif root.right==None:
l = self.helper(root.left)
if l and root.val==root.left.val:
self.res += 1
return True
else:
return False
else:
l = self.helper(root.left)
r = self.helper(root.right)
if l and r and root.val==root.left.val and root.val==root.right.val:
self.res += 1
return True
else:
return False