Easy to understand Python Solution


  • 0
    J
    def countUnivalSubtrees(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        frontier = [root]
        res = 0
        while root and frontier: #loop through all the nodes
            next = []
            for u in frontier:
                if self.helper(u.left,u) and self.helper(u.right,u):
                    res += 1
                if u.left:
                    next.append(u.left)
                if u.right:
                    next.append(u.right)
            frontier = next
        return res
        
    def helper(self, node, parent):
        if not node:
            return True
        elif node.val != parent.val:
            return False
        
        return self.helper(node.left,node) and self.helper(node.right,node)

Log in to reply
 

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