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

[Locked] Count Univalue Subtrees

2016-02-24 12:21 561 查看
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
.

分析:

  有点像自低向上的动态规划,既然是自底向上,看来用递归访问树的节点无疑可以解决问题

代码:

bool dfs(TreeNode *node, int &count) {
if(!node)
return true;
//一定要让保证其先递归,达到最底层节点,然后作后续处理
bool goodleft = dfs(node->left, count), goodright = dfs(node->right, count);
//与左右节点值相同,且左右子树是值相同的树,则以该节点为根节点的树也是值相同的树
if(goodleft && goodright && (!node->left || node->val == node->left->val) && (!node->right || node->val == node->right->val)) {
count++;
return true;
}
return false;
}
int count(TreeNode *node) {
int num = 0;
dfs(node, num);
return num;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: