Count Univalue Subtrees

MediumTreesdfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given the root of a binary tree, return how many of its subtrees are **univalue**. A subtree consists of a node together with all of its descendants. It is univalue when every node in it carries the same value. Every leaf is therefore a univalue subtree on its own, and an empty tree has 0 univalue subtrees.

Examples

Input: root = [5,1,5,5,5,null,5]
Output: 4
The three leaves (all 5) count, and so does the right child 5 with its single child 5. The subtrees rooted at 1 and at the root mix values.
Input: root = [5,5,5,5,5,null,5]
Output: 6
Every node's subtree contains only 5s.
Input: root = []
Output: 0
No nodes, no subtrees.

Constraints

  • 0 <= number of nodes <= 1000
  • -1000 <= Node.val <= 1000

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More dfs problems