Count Uni-Valued Subtrees
Problem statement
Given the root of a binary tree, return the number of subtrees whose nodes all have the same value.
Every node defines one subtree consisting of that node and all of its descendants. A leaf is therefore always a uni-valued subtree.
Function
countUnivalSubtrees(root: TreeNode) → intExamples
Example 1
root = [5,1,5,5,5,null,5]return = 4The three leaf fives and the right subtree rooted at five are uni-valued.
Example 2
root = [1]return = 1A leaf is uni-valued.
Example 3
root = []return = 0An empty tree contains no subtree.
Constraints
- The tree contains between
0and500nodes. -1000 ≤ Node.val ≤ 1000.