## Tree - 250. Count Univalue Subtrees

Published on with 0 views and 0 comments

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

Example1

``````Input:  root = {5,1,5,5,5,#,5}
Output: 4
Explanation:
5
/ \
1   5
/ \   \
5   5   5
``````

Example2

``````Input:  root = {1,3,2,4,5,#,6}
Output: 3
Explanation:
1
/ \
3   2
/ \   \
4   5   6
``````

go：

``````/**
* Definition for a binary tree node.
* type TreeNode struct {
*     Val int
*     Left *TreeNode
*     Right *TreeNode
* }
*/

/**
* @param root: the given tree
* @return: the number of uni-value subtrees.
*/
func countUnivalSubtrees (root *TreeNode) int {
var res = 0
if root != nil {
_ = isUnivalSubtrees(root, &res)
}
return res
}

func isUnivalSubtrees(node *TreeNode, res *int) bool {
if node == nil {
return true
}

left := isUnivalSubtrees(node.Left, res)
right := isUnivalSubtrees(node.Right, res)

if left && right &&
(node.Left == nil || node.Val == node.Left.Val) &&
(node.Right == nil || node.Val == node.Right.Val) {
*res++
return true
}

return false
}
``````