原题网址:https://leetcode.com/problems/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
.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int count;
private Integer unival(TreeNode root) {
boolean unival = true;
if (root.left != null) {
Integer left = unival(root.left);
if (left == null || root.val != left) unival = false;
}
if (root.right != null) {
Integer right = unival(root.right);
if (right == null || root.val != right) unival = false;
}
if (!unival) return null;
count ++;
return root.val;
}
public int countUnivalSubtrees(TreeNode root) {
if (root == null) return 0;
unival(root);
return count;
}
}
类似方法:递归函数返回是否uni
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int count;
private boolean unival(TreeNode root) {
boolean uni = true;
if (root.left != null) uni &= unival(root.left) && root.val == root.left.val;
if (root.right != null) uni &= unival(root.right) && root.val == root.right.val;
if (uni) count ++;
return uni;
}
public int countUnivalSubtrees(TreeNode root) {
if (root == null) return 0;
unival(root);
return count;
}
}