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,
1
| 5
/ \
1 5
/ \ \
5 5 5
|
return
4
.
Based on the description, the tree must consider its all children. So it is easier.
Go recursion with each node, and call a function to judge if it is a uni-value subtree.
# Time: O(n) # Space: O(h) # # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param {TreeNode} root # @return {integer} def countUnivalSubtrees(self, root): [is_uni, count] = self.isUnivalSubtrees(root, 0); return count; def isUnivalSubtrees(self, root, count): if not root: return [True, count] [left, count] = self.isUnivalSubtrees(root.left, count) [right, count] = self.isUnivalSubtrees(root.right, count) if self.isSame(root, root.left, left) and \ self.isSame(root, root.right, right): count += 1 return [True, count] return [False, count] def isSame(self, root, child, is_uni): return not child or (is_uni and root.val == child.val)
No comments:
Post a Comment