662.maximum-width-of-binary-tree.go 719 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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 widthOfBinaryTree(root *TreeNode) int {
  10. m := make(map[int][]int)
  11. helper(root, 0, 0, m)
  12. max := 0
  13. for _, v := range m {
  14. max = maxInt(max, v[1]-v[0])
  15. }
  16. return max + 1
  17. }
  18. func helper(root *TreeNode, x, y int, m map[int][]int) {
  19. if root == nil {
  20. return
  21. }
  22. if v, ok := m[y]; ok {
  23. v[0] = minInt(v[0], x)
  24. v[1] = maxInt(v[1], x)
  25. } else {
  26. m[y] = []int{x, x}
  27. }
  28. helper(root.Left, x<<1, y+1, m)
  29. helper(root.Right, (x<<1)|1, y+1, m)
  30. }
  31. func minInt(x, y int) int {
  32. if x < y {
  33. return x
  34. }
  35. return y
  36. }
  37. func maxInt(x, y int) int {
  38. if x < y {
  39. return y
  40. }
  41. return x
  42. }