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
.
思路:首先明白题目是什么意思,就是所有的node的值是一样的,就可以。自然而然,想到自底向上的传递方法。传什么,这是个问题,刚开始想传值,这里一想比较复杂,其实只需要传递subtree是否是univalue tree,然后判断当前root和左右子树的关系就可以了,然后再继续往上传。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int countUnivalSubtrees(TreeNode root) {
if(root == null) {
return 0;
}
int[] res = {0};
dfs(root, res);
return res[0];
}
private boolean dfs(TreeNode root, int[] res) {
if(root == null) {
return true;
}
boolean leftuni = dfs(root.left, res);
boolean rightuni = dfs(root.right, res);
if(leftuni && rightuni) {
if(root.left != null && root.val != root.left.val) {
return false;
}
if(root.right != null && root.val != root.right.val) {
return false;
}
res[0]++;
return true;
} else {
return false;
}
}
}