655.print-binary-tree.go 833 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  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 printTree(root *TreeNode) [][]string {
  10. if root == nil {
  11. return [][]string{}
  12. }
  13. depth := 0
  14. helper(root, 0, &depth)
  15. res := make([][]string, depth)
  16. for i := range res {
  17. res[i] = make([]string, 1<<uint(depth)-1)
  18. }
  19. printer(root, len(res[0])/2, 0, 1<<uint(depth-2), res)
  20. return res
  21. }
  22. func printer(root *TreeNode, x, y, det int, res [][]string) {
  23. if root == nil {
  24. return
  25. }
  26. res[y][x] = strconv.Itoa(root.Val)
  27. printer(root.Left, x-det, y+1, det>>1, res)
  28. printer(root.Right, x+det, y+1, det>>1, res)
  29. }
  30. func helper(root *TreeNode, y int, depth *int) {
  31. if root == nil {
  32. return
  33. }
  34. y++
  35. if *depth < y {
  36. *depth = y
  37. }
  38. helper(root.Left, y, depth)
  39. helper(root.Right, y, depth)
  40. }