Count Univalue Subtrees
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
return 4.
Solution
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int countUnivalSubtrees(TreeNode root) {
if (root == null) return 0;
int[] result = helper(root);
return result[0] + result[1];
}
private int[] helper(TreeNode root) {
if (root == null) return new int[2];
int[] leftArray = helper(root.left);
int[] rightArray = helper(root.right);
int[] result = new int[2];
if (root.left != null && root.right != null) {
if (leftArray[0] == 1 && rightArray[0] == 1 && root.val == root.left.val && root.val == root.right.val) {
result[0] = 1;
}
} else if (root.left != null) {
if (leftArray[0] == 1 && root.val == root.left.val) {
result[0] = 1;
}
} else if (root.right != null) {
if (rightArray[0] == 1 && root.val == root.right.val) {
result[0] = 1;
}
} else {
result[0] = 1;
}
result[1] = leftArray[1] + rightArray[1] + leftArray[0] + rightArray[0];
return result;
}
}