1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| class Solution { public int countUnivalSubtrees(TreeNode root) { if (root == null) { return 0; }
int count = 0; count += countUnivalSubtrees(root.left); count += countUnivalSubtrees(root.right);
count += isSameValueTree(root) ? 1 : 0;
return count; }
private boolean isSameValueTree(TreeNode root) { if (root == null) { return true; }
if (root.left != null && root.left.val != root.val) { return false; } if (root.right != null && root.right.val != root.val) { return false; }
return isSameValueTree(root.left) && isSameValueTree(root.right); } }
|
References
250. Count Univalue Subtrees