helper.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package main
  2. import (
  3. "strconv"
  4. )
  5. // ListNode ...
  6. type ListNode struct {
  7. Val int
  8. Next *ListNode
  9. }
  10. // TreeNode ...
  11. type TreeNode struct {
  12. Val int
  13. Left *TreeNode
  14. Right *TreeNode
  15. }
  16. // Interval ...
  17. type Interval struct {
  18. Start int
  19. End int
  20. }
  21. func abs(x int) int {
  22. if x < 0 {
  23. return -x
  24. }
  25. return x
  26. }
  27. func maxInt(x, y int) int {
  28. if x > y {
  29. return x
  30. }
  31. return y
  32. }
  33. func minInt(x, y int) int {
  34. if x < y {
  35. return x
  36. }
  37. return y
  38. }
  39. func toLinkedList(num []int) *ListNode {
  40. length := len(num)
  41. if length == 0 {
  42. return nil
  43. }
  44. head := ListNode{num[0], nil}
  45. curr := &head
  46. for i := 1; i < length; i++ {
  47. curr.Next = &ListNode{num[i], nil}
  48. curr = curr.Next
  49. }
  50. return &head
  51. }
  52. func printList(head *ListNode) {
  53. curr := head
  54. for curr != nil {
  55. print(strconv.FormatInt(int64(curr.Val), 10), " ")
  56. curr = curr.Next
  57. }
  58. println()
  59. }
  60. func printTree(root *TreeNode) { // Level order traversal
  61. if root == nil {
  62. println("nil")
  63. return
  64. }
  65. queue := make([]*TreeNode, 0) // Important!
  66. queue = append(queue, root)
  67. for len(queue) != 0 {
  68. curr := queue[0]
  69. queue = queue[1:] // Dequeue
  70. if curr == nil {
  71. print("nil ")
  72. continue
  73. }
  74. print(curr.Val, " ")
  75. if curr.Left != nil {
  76. queue = append(queue, curr.Left)
  77. } else if curr.Right != nil {
  78. queue = append(queue, nil)
  79. }
  80. if curr.Right != nil {
  81. queue = append(queue, curr.Right)
  82. } else if curr.Left != nil {
  83. queue = append(queue, nil)
  84. }
  85. }
  86. println()
  87. }
  88. func printBoard(board [][]byte) {
  89. for _, row := range board {
  90. for _, grid := range row {
  91. print(string(grid), " ")
  92. }
  93. println()
  94. }
  95. }