FunctionRacerProblemsRace

Count Univalue Subtrees

MediumTreesPython, JavaScript, TypeScript, Java, C++

You are given the root of a binary tree. A subtree is the tree formed by one node and all its descendants. It is univalue if every node in it has the same value. A leaf alone is univalue. Return how many univalue subtrees the tree contains. An empty tree gives 0.

Trees appear in the tests in level order, with null for a missing child, like [3,9,20,null,null,15,7]. Each node is a TreeNode with .val, .left and .right; the class is already defined for you.

Example 1

root [5,1,5,5,5,null,5]
returns 4

The three leaves are univalue, and so is the right 5 with its child 5. That is 4.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Trees problems