@@ -0,0 +1,1724 @@
+#!/usr/bin/env python%0A# encoding: utf-8%0A%0A%22%22%22%0Acount-univalue-subtrees.py%0A%0ACreated by Shuailong on 2016-05-15.%0A%0Ahttps://leetcode.com/problems/count-univalue-subtrees/.%0A%0A%22%22%22%0A%0A'''TODO: performance need improving.'''%0A%0A%0A# Definition for a binary tree node.%0Aclass TreeNode(object):%0A    def __init__(self, x):%0A        self.val = x%0A        self.left = None%0A        self.right = None%0A%0A%0Aclass Solution(object):%0A    def isUnivalSubtree(self, root):%0A        '''%0A        :type root: TreeNode%0A        :rtype: int %7C None%0A        '''%0A%0A        if root is None:%0A            return None%0A        if root.left is None and root.right is None:%0A            return root.val%0A%0A        lval = self.isUnivalSubtree(root.left)%0A        rval = self.isUnivalSubtree(root.right)%0A%0A        if root.val == lval and root.val == rval:%0A            return root.val%0A%0A        if root.left is None and root.val == rval or root.right is None and root.val == lval:%0A            return root.val%0A%0A        return None%0A%0A    def countUnivalSubtrees(self, root):%0A        %22%22%22%0A        :type root: TreeNode%0A        :rtype: int%0A        %22%22%22%0A        if root is None:%0A            return 0%0A        if root.left is None and root.right is None:%0A            return 1%0A%0A        res = self.countUnivalSubtrees(root.left) + self.countUnivalSubtrees(root.right)%0A        if self.isUnivalSubtree(root):%0A            res += 1%0A        return res%0A%0A%0Adef main():%0A    solution = Solution()%0A    t1 = TreeNode(5)%0A    t2 = TreeNode(1)%0A    t3 = TreeNode(5)%0A    t4 = TreeNode(5)%0A    t5 = TreeNode(5)%0A    t6 = TreeNode(5)%0A    t1.left = t2%0A    t1.right = t3%0A    t2.left = t4%0A    t2.right = t5%0A    t3.right = t6%0A    root = t1%0A    print solution.countUnivalSubtrees(root)%0A%0A%0Aif __name__ == '__main__':%0A    main()%0A

solve 1 problem