[leetcode]250. 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.

Example :

Input:  root = [5,1,5,5,5,null,5]

              5
/ \
1 5
/ \ \
5 5 5 Output: 4

题意:

给定一棵二叉树,求所有节点都同值的二叉树。

[leetcode]250. Count Univalue Subtrees统计节点值相同的子树

思路:

dfs

代码:

 class Solution {
int result;
public int countUnivalSubtrees(TreeNode root) {
result = 0;
helper(root);
return result;
} private boolean helper(TreeNode node){
if(node == null ) return true; boolean left = helper(node.left);
boolean right = helper(node.right); if(left&&right){
if ((node.left!= null && node.val != node.left.val) || (node.right!= null && node.val != node.right.val) ){
return false;
}
result++;
return true;
}
return false;
}
}
上一篇:Qt之QLabel


下一篇:DevExpress的TreeList怎样给树节点设置图标