helper.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. func abs(x int) int {
  17. if x < 0 {
  18. return -x
  19. }
  20. return x
  21. }
  22. func maxInt(x, y int) int {
  23. if x > y {
  24. return x
  25. }
  26. return y
  27. }
  28. func minInt(x, y int) int {
  29. if x < y {
  30. return x
  31. }
  32. return y
  33. }
  34. func list2str(head *ListNode) string {
  35. curr := head
  36. str := ""
  37. for curr != nil {
  38. str += strconv.FormatInt(int64(curr.Val), 10) + " "
  39. curr = curr.Next
  40. }
  41. return str
  42. }
  43. func printTree(root *TreeNode) { // Level order traversal
  44. if root == nil {
  45. println("nil")
  46. return
  47. }
  48. queue := make([]*TreeNode, 0) // Important!
  49. queue = append(queue, root)
  50. for len(queue) != 0 {
  51. curr := queue[0]
  52. queue = queue[1:] // Dequeue
  53. if curr == nil {
  54. print("nil ")
  55. continue
  56. }
  57. print(curr.Val, " ")
  58. if curr.Left != nil {
  59. queue = append(queue, curr.Left)
  60. } else if curr.Right != nil {
  61. queue = append(queue, nil)
  62. }
  63. if curr.Right != nil {
  64. queue = append(queue, curr.Right)
  65. } else if curr.Left != nil {
  66. queue = append(queue, nil)
  67. }
  68. }
  69. println()
  70. }