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,
5
/ \
1 5
/ \ \
5 5 5
return4
.
tag: binary tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private class MyTree{
int val;
public MyTree(int val){
this.val = val;
}
}
int ans = 0;
public int countUnivalSubtrees(TreeNode root) {
if (root == null) return 0;
dfs(root);
return ans;
}
private int dfs(TreeNode root){
if (root == null) return Integer.MAX_VALUE;
if (root.left == null && root.right == null){
ans++;
return root.val;
}
int leftRes = dfs(root.left);
int rightRes = dfs(root.right);
if ( (root.left == null || root.val == leftRes) && (root.right == null || root.val == rightRes) ){
ans++;
return root.val;
}
else{
return Integer.MAX_VALUE;
}
}
}