Skip to content

Instantly share code, notes, and snippets.

@waynejo
Created August 26, 2018 13:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save waynejo/4a120f75b7f2417d6f269da18f795d9e to your computer and use it in GitHub Desktop.
Save waynejo/4a120f75b7f2417d6f269da18f795d9e to your computer and use it in GitHub Desktop.
func max(v0 int, v1 int) int {
if v0 < v1 {
return v1
}
return v0
}
func longestUnivaluePathInternal(root *TreeNode, value int) int {
if nil == root || root.Val != value{
return 0
}
leftMax := longestUnivaluePathInternal(root.Left, value)
rightMax := longestUnivaluePathInternal(root.Right, value)
return max(leftMax, rightMax) + 1
}
func longestUnivaluePath(root *TreeNode) int {
if nil == root {
return 0
}
var result = longestUnivaluePathInternal(root.Left, root.Val) + longestUnivaluePathInternal(root.Right, root.Val)
result = max(result, longestUnivaluePath(root.Left))
return max(result, longestUnivaluePath(root.Right))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment