10 lines Python


  • 0
    B
    class Solution(object):
        count = 0
        def countUnivalSubtrees(self, root):
            if root:
                self.helper(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.