Short Python solution

  • 0
    class Solution(object):
        def countUnivalSubtrees(self, root):
            :type root: TreeNode
            :rtype: int
            # slightly shorttend code
            # method 1
            count = [0]
            def check(root):
                if not root:
                    return True
                left = check(root.left)
                right = check(root.right)
                if (left and right and (not root.left or root.left.val==root.val) and (not root.right or root.right.val==root.val)):
                    return True
            return count[0]

Log in to reply

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