Created
August 26, 2018 13:42
-
-
Save waynejo/4a120f75b7f2417d6f269da18f795d9e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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