# Tree - 687. Longest Univalue Path

687. Longest Univalue Path

Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.

The length of path between two nodes is represented by the number of edges between them.

Example 1:

Input:

``````              5
/ \
4   5
/ \   \
1   1   5

``````

Output: 2

Example 2:

Input:

``````              1
/ \
4   5
/ \   \
4   4   5

``````

Output: 2

Note: The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.

go：

``````/**

* Definition for a binary tree node.
* type TreeNode struct {
*     Val int
*     Left *TreeNode
*     Right *TreeNode
* }
*/
func longestUnivaluePath(root *TreeNode) int {
if root == nil {
return 0
}

var res int
univaluePath(root, &res)

return res
}

func univaluePath(node *TreeNode, res *int) int {
if node == nil {
return 0
}

leftLen := univaluePath(node.Left, res)
rightLen := univaluePath(node.Right, res)

var leftPathLen, rightPathLen int
if node.Left != nil && node.Val == node.Left.Val {
leftPathLen = leftLen + 1
}
if node.Right != nil && node.Val == node.Right.Val {
rightPathLen = rightLen + 1
}

*res = max(*res, leftPathLen + rightPathLen)

return max(leftPathLen, rightPathLen)

}

func max(i, j int) int {
if i > j {
return i
}

return j
}
``````

Nothing just happens, it's all part of a plan.