您的位置:首页 > 产品设计 > UI/UE

LeetCode 250. Count Univalue Subtrees

2017-01-14 08:14 267 查看
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.

思路:

1. univalue subtree是指子树的每个节点的值都相等。例子中三个leaf node是子树且节点值相等,另外还有

5
\
5


2. 需要dfs遍历,提取信息,做出判断。提取的信息是左右子树是否univalue或NULL,以及univalue的值是多少。如果root的值等于左右子树的univalue,则总的子树个数+1;否则传递信息表明当前不是univalue subtree

int countUnivalSubtrees(TreeNode* root) {
//
int res=0;
int value=root->val;
helper(root,res,value);
return res;
}

bool helper(TreeNode* root,int&res,int&value){
//
if(!root) return true;
int lvalue=root->val, rvalue=root->val;
if(helper(root->left,res,lvalue)&&helper(root->right,res,rvalue)){
if(lvalue==rvalue&&lvalue==root->value){
res+=1;
value=root->val;
return true;
}
}
return false;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode tree dfs