不讲武德地使用了set()函数
Given the root
of a binary tree, return the number of uni-valuesubtrees.
A uni-value subtree means all nodes of the subtree have the same value.
Example 1:
Input: root = [5,1,5,5,5,null,5] Output: 4
Example 2:
Input: root = [] Output: 0
Example 3:
Input: root = [5,5,5,5,5,null,5] Output: 6
Constraints:
- The number of the node in the tree will be in the range
[0, 1000]
. -1000 <= Node.val <= 1000
class Solution:
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
node, output = root, []
while node:
if not node.left:
output.append(node.val)
node = node.right
else:
predecessor = node.left
while predecessor.right and predecessor.right is not node:
predecessor = predecessor.right
if not predecessor.right:
output.append(node.val)
predecessor.right = node
node = node.left
else:
predecessor.right = None
node = node.right
return output
def countUnivalSubtrees(self, root):
if not root:
return 0
output = len(set(self.preorderTraversal(root)))
cnt = 1 if output == 1 else 0
print
if root.left == None and root.right == None:
return 1
else:
cnt = cnt + self.countUnivalSubtrees(root.left) + self.countUnivalSubtrees(root.right)
return cnt