687.longest-univalue-path.go 680 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /**
  2. * Definition for a binary tree node.
  3. * type TreeNode struct {
  4. * Val int
  5. * Left *TreeNode
  6. * Right *TreeNode
  7. * }
  8. */
  9. func longestUnivaluePath(root *TreeNode) int {
  10. max := 0
  11. if root == nil {
  12. return max
  13. }
  14. helper(root, &max)
  15. return max - 1
  16. }
  17. func helper(root *TreeNode, max *int) int {
  18. l, r := 0, 0
  19. if root.Left != nil {
  20. l = helper(root.Left, max)
  21. if root.Left.Val != root.Val {
  22. l = 0
  23. }
  24. }
  25. if root.Right != nil {
  26. r = helper(root.Right, max)
  27. if root.Right.Val != root.Val {
  28. r = 0
  29. }
  30. }
  31. if *max < 1+l+r {
  32. *max = 1 + l + r
  33. }
  34. return 1 + maxInt(l, r) // !!important
  35. }
  36. func maxInt(x, y int) int {
  37. if x < y {
  38. return y
  39. }
  40. return x
  41. }