/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func longestUnivaluePath(root *TreeNode) int { max := 0 if root == nil { return max } helper(root, &max) return max - 1 } func helper(root *TreeNode, max *int) int { l, r := 0, 0 if root.Left != nil { l = helper(root.Left, max) if root.Left.Val != root.Val { l = 0 } } if root.Right != nil { r = helper(root.Right, max) if root.Right.Val != root.Val { r = 0 } } if *max < 1+l+r { *max = 1 + l + r } return 1 + maxInt(l, r) // !!important } func maxInt(x, y int) int { if x < y { return y } return x }