Problem 456808 · easy · Level 04 Non-Linear Data Structures

One Colour on Every Bauble

binary trees · traversal · predicates

The baubles on a decorated tree are the nodes of a binary tree, and each node's value is a colour code. The tree looks tidy only when every bauble has the same colour (the tree is univalued). Given the root, return True if it is and False otherwise. A bare tree with no nodes counts as tidy.

Examples

    7
   / \
  7   7
   \  /
    7 7

Input:  root = build_tree([7, 7, 7, None, 7, 7])
Output: True
      3
     / \
    3   3
   /   /
  3   6

Input:  root = build_tree([3, 3, 3, 3, None, 6])
Output: False

Constraints

  • 0 <= number of nodes <= 2000
  • -10**4 <= node.val <= 10**4
  • Target complexity: O(n) time.

Goals

  • Carry a reference value through the traversal
  • Stop early on the first mismatch
  • Decide the answer for an empty tree
Starting Python…