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.
The condition for a subtree to be a uni-value subtree is that:
(The left subtree has to be a uni-value subtree or null) && (right subtree has to be a uni-value subtree or null) && (left null || left.val== root.val) && (right null || right.val==root.val)
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public int countUnivalSubtrees(TreeNode root) { 12 if (root == null) return 0; 13 ArrayList<Integer> sum = new ArrayList<Integer>(); 14 sum.add(0); 15 helper(root, sum); 16 return sum.get(0); 17 } 18 19 public boolean helper(TreeNode root, ArrayList<Integer> sum) { 20 if (root == null) return true; 21 boolean left = helper(root.left, sum); 22 boolean right = helper(root.right, sum); 23 if (left && right && (root.left==null || root.val==root.left.val) && (root.right==null || root.val==root.right.val)) { 24 sum.set(0, sum.get(0)+1); 25 return true; 26 } 27 return false; 28 } 29 }