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
.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { //post order; int max = 1; public int countUnivalSubtrees(TreeNode root) { if(root == null) return 0; if(root.left == null && root.right == null) return 1; int res = countUnivalSubtrees(root.left) + countUnivalSubtrees(root.right); return isUniTree(root) ? res +1 : res; } public boolean isUniTree(TreeNode root){ if(root == null) return true; if(root.left == null && root.right == null) return true; if(isUniTree(root.left) && isUniTree(root.right)){ if(root.left != null && root.right != null){ return (root.left.val == root.right.val && root.right.val == root.val); }else if(root.left != null) return root.left.val == root.val; else return root.right.val == root.val; } return false; } }