654.maximum-binary-tree.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /**
  2. * Definition for a binary tree node.
  3. * type TreeNode struct {
  4. * Val int
  5. * Left *TreeNode
  6. * Right *TreeNode
  7. * }
  8. */
  9. type maxHeap []int
  10. func (h maxHeap) Len() int { return len(h) }
  11. func (h maxHeap) Less(i, j int) bool { return h[j] < h[i] }
  12. func (h maxHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
  13. func (h *maxHeap) Push(x interface{}) {
  14. *h = append(*h, x.(int))
  15. }
  16. func (h *maxHeap) Pop() interface{} {
  17. l := h.Len()
  18. x := (*h)[l-1]
  19. *h = (*h)[:l-1]
  20. return x
  21. }
  22. func constructMaximumBinaryTree(nums []int) *TreeNode {
  23. if len(nums) == 0 {
  24. return (*TreeNode)(nil)
  25. }
  26. m := make(map[int]int)
  27. var h maxHeap
  28. for i, v := range nums {
  29. m[v] = i
  30. heap.Push(&h, v)
  31. }
  32. root := TreeNode{heap.Pop(&h).(int), nil, nil}
  33. for h.Len() != 0 {
  34. curr := &root
  35. v := heap.Pop(&h).(int)
  36. i := m[v]
  37. for {
  38. j := m[curr.Val]
  39. if i < j {
  40. if curr.Left == nil {
  41. curr.Left = &TreeNode{v, nil, nil}
  42. break
  43. }
  44. curr = curr.Left
  45. } else {
  46. if curr.Right == nil {
  47. curr.Right = &TreeNode{v, nil, nil}
  48. break
  49. }
  50. curr = curr.Right
  51. }
  52. }
  53. }
  54. return &root
  55. }