Guest User

Untitled

a guest
Jun 19th, 2018
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. /*
  2.  
  3. 662. Maximum Width of Binary Tree
  4.  
  5. Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels. The binary tree has the same structure as a full binary tree, but some nodes are null.
  6.  
  7. The width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where the null nodes between the end-nodes are also counted into the length calculation.
  8.  
  9. Example 1:
  10. Input:
  11.  
  12. 1
  13. / \
  14. 3 2
  15. / \ \
  16. 5 3 9
  17.  
  18. Output: 4
  19. Explanation: The maximum width existing in the third level with the length 4 (5,3,null,9).
  20. Example 2:
  21. Input:
  22.  
  23. 1
  24. /
  25. 3
  26. / \
  27. 5 3
  28.  
  29. Output: 2
  30. Explanation: The maximum width existing in the third level with the length 2 (5,3).
  31. Example 3:
  32. Input:
  33.  
  34. 1
  35. / \
  36. 3 2
  37. /
  38. 5
  39.  
  40. Output: 2
  41. Explanation: The maximum width existing in the second level with the length 2 (3,2).
  42. Example 4:
  43. Input:
  44.  
  45. 1
  46. / \
  47. 3 2
  48. / \
  49. 5 9
  50. / \
  51. 6 7
  52. Output: 8
  53. Explanation:The maximum width existing in the fourth level with the length 8 (6,null,null,null,null,null,null,7).
  54.  
  55.  
  56. Note: Answer will in the range of 32-bit signed integer.
  57. */
  58.  
  59. /**
  60. * Definition for a binary tree node.
  61. * type TreeNode struct {
  62. * Val int
  63. * Left *TreeNode
  64. * Right *TreeNode
  65. * }
  66. */
  67.  
  68. type TreeNodeWithNumber struct {
  69. Node *TreeNode
  70. Val int
  71. }
  72. func widthOfBinaryTree(root *TreeNode) int {
  73. if root == nil {
  74. return 0
  75. }
  76.  
  77. q := []*TreeNodeWithNumber{&TreeNodeWithNumber{root, 1}}
  78. _max := 0
  79. for len(q) > 0 {
  80. _max = max(_max, q[len(q)-1].Val-q[0].Val+1)
  81. nxt := []*TreeNodeWithNumber{}
  82.  
  83. for _, tn := range q {
  84. t := tn.Node
  85. v := tn.Val
  86. if t.Left != nil {
  87. nxt = append(nxt, &TreeNodeWithNumber{t.Left, v*2})
  88. }
  89. if t.Right != nil {
  90. nxt = append(nxt, &TreeNodeWithNumber{t.Right, v*2+1})
  91. }
  92. }
  93. q = nxt
  94. }
  95. return _max
  96. }
  97. func max(a , b int) int {
  98. if a > b {
  99. return a
  100. }
  101. return b
  102.  
  103. }
Add Comment
Please, Sign In to add comment