250 LeetCode Java: Count Univalue Subtrees – Medium
Problem:
Given a binary tree, count the number of uni-value subtrees.
A Uni-value subtree means all nodes of the subtree have the same value.
For example: Given binary tree,
return 4.
Thoughts:
This problem can be solved by using recursion easily. We will need a function to return if a tree is having all the same values. Say the function is isUni(), then the condition for a tree to be a univalue tree is that node.left and node.right are both univalue tree and they have the same val with the node.
Also we will need a counter to keep the numbers of univalue subtree. In the solution below, I am using a class property. If not, we can use a TreeNode variable and pass it into isUni() so that each time inside of isUni function, it’s modifying the same variable.
Solutions:
Last updated