Problem statement

https://binarysearch.com/problems/Univalue-Tree/

Solution

Equal to Leetcode 0965. Univalued Binary Tree.

Complexity

It is O(n) for time and O(h) for space.

Code

class Solution:
    def solve(self, root):
        if not root: return True
        if root.left and root.left.val != root.val: return False
        if root.right and root.right.val != root.val: return False
        return self.solve(root.left) and self.solve(root.right)