Ctrl K

Same-Value Subtrees

Medium
You are given the root of a binary tree. The subtree of a node is that node together with all of its descendants. A subtree is uniform if every node in it holds the same value. Return the number of uniform subtrees. Every leaf is a uniform subtree. An empty tree has none.
Example 1
root=tree_node([3, 3, 7, 3, 3, None, 7]) → 5

The three leaves are uniform, and so are the subtree of the left 3 (all its nodes are 3) and the subtree of the right 7. The whole tree mixes 3 and 7. The answer is 5.

Example 2
root=tree_node([4, 4, 4, None, None, 1]) → 2

The left leaf 4 and the leaf 1 are uniform. The right 4 has a child 1, so neither its subtree nor the whole tree counts. The answer is 2.

Example 3
root=tree_node([]) → 0
Constraints
  • 0 ≤ number of nodes ≤ 1000
  • -1000 ≤ Node.val ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsIs It a Search Tree? MediumTwo Mixed-Up Nodes MediumAll Leaf Paths With a Given Total MediumTree Into a Right Chain MediumDigit Branch Totals Medium
loading Python…
Input
root=tree_node([3, 3, 7, 3, 3, None, 7])
Expected
5

Run checks the first 3 tests in your browser. Submit checks all 97 tests on the server, hidden ones included.