1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// @Title: 最长同值路径 (Longest Univalue Path)
// @Author: 15816537946@163.com
// @Date: 2020-06-25 07:15:36
// @Runtime: 84 ms
// @Memory: 6.9 MB
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
 func longestUnivaluePath(root *TreeNode) int {
	var path int
	var helper func(*TreeNode) int

	helper = func(node *TreeNode) int {
		if node == nil {
			return 0
		}

		left := helper(node.Left)
		right := helper(node.Right)
		var leftPath, rightPath int
		if node.Left != nil && node.Left.Val == node.Val {
			leftPath = left + 1
		}
		if node.Right != nil && node.Right.Val == node.Val {
			rightPath = right + 1
		}
		path = max(path, leftPath+rightPath)
		return max(leftPath, rightPath)
	}
	helper(root)
	return path
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}