题目描述:
Given the root of a binary tree, return the number of uni-value subtrees.
A uni-value subtree means all nodes of the subtree have the same value.
Example 1:
Input: root = [5,1,5,5,5,null,5]
Output: 4
Example 2:
Input: root = [5,5,5,5,5,null,5]
Output: 6
Constraints:
The numbrt of the node in the tree will be in the range [0, 1000].
-1000 <= Node.val <= 1000
Time complexity: O(n)
Space complexity : O(H)
DFS:
同值子树的两种情况:
- 此树没有叶子结点
- 所有的叶子结点的值是同值子树而且所有的节点值都相同
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int count;
public int countUnivalSubtrees(TreeNode root) {
count = 0;
helper(root);
return count;
}
boolean helper(TreeNode root) {
if(root == null) return true;
boolean left = helper(root.left);
boolean right = helper(root.right);
if(left && right &&
(root.left == null || root.val == root.left.val) &&
(root.right == null || root.val == root.right.val)){
count++;
return true;
}
return false;
}
}