11 lines of Python DFS solution


  • 1
    C
    def countUnivalSubtrees(root):
        def dfs(root):
            if root == None:
                return True
            l, r = dfs(root.left), dfs(root.right)
            lval = root.left.val if root.left else root.val
            rval = root.right.val if root.right else root.val
            prev, cnt[0] = cnt[0], cnt[0] + (root.val == lval == rval and l and r)
            return prev != cnt[0]
    
        cnt = [0]
        dfs(root)
        return cnt[0]

Log in to reply
 

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