Univalued Binary Tree

Problem Id: 965 Difficulty: Easy Tag: Tree


Use a DFS with 2 additional return value value and is_univalue.


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isUnivalTree(self, root: TreeNode) -> bool:
        return self._helper(root)[1]

    def _helper(self, node):
        if node is None:
            return None, True
        l = self._helper(node.left)
        r = self._helper(node.right)
        if l[1] and r[1]:
            if l[0] is not None and l[0] != node.val:
                return None, False
            if r[0] is not None and r[0] != node.val:
                return None, False
            return node.val, True
        return None, False