Simple Python Solution


  • 0
    L
    class Solution(object):
        def countUnivalSubtrees(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            if not root: return 0
            return int(self.match(root,root.val) if root else 0) + int(self.countUnivalSubtrees(root.left))+int(self.countUnivalSubtrees(root.right))
            
        def match(self,root,v):
            if not root:return True
            return root.val==v and self.match(root.left,v) and self.match(root.right,v)

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.