543.diameter-of-binary-tree.go 471 B

123456789101112131415161718192021222324252627282930
  1. var max int = 0
  2. /**
  3. * Definition for a binary tree node.
  4. * type TreeNode struct {
  5. * Val int
  6. * Left *TreeNode
  7. * Right *TreeNode
  8. * }
  9. */
  10. func diameterOfBinaryTree(root *TreeNode) int {
  11. max = 0
  12. postorder(root, &max)
  13. return
  14. }
  15. func postorder(root *TreeNode, max *int) int {
  16. if root == nil {
  17. return -1
  18. }
  19. l := postorder(root.Left, max) + 1
  20. r := postorder(root.Right, max) + 1
  21. if *max < l+r {
  22. *max = l + r
  23. }
  24. if l < r {
  25. return r
  26. }
  27. return l
  28. }