python bottom up O(n)


  • 0
    Z
    class Solution(object):
        def countUnivalSubtrees(self, root):
            self.count = 0
            def helper(root):
                if not root: return True
                l, r = helper(root.left), helper(root.right)
                if not l or not r or root.left and root.val != root.left.val or root.right and root.val != root.right.val:
                    return False
                self.count += 1
                return True
            helper(root)
            return self.count

Log in to reply
 

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