10 lines Python

  • 0
    class Solution(object):
        count = 0
        def countUnivalSubtrees(self, root):
            if root:
            return self.count
        def helper(self, root):
            leftIsGood = not root.left or (self.helper(root.left) and root.val == root.left.val)
            rightIsGood = not root.right or (self.helper(root.right) and root.val == root.right.val)
            self.count += int(leftIsGood and rightIsGood)
            return leftIsGood and rightIsGood

Log in to reply

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