606. 根据二叉树创建字符串

image.png
1 先序遍历采用栈结构,每次把根节点出栈的时候 按照先右节点再左节点的方式入栈。
2 之前的先序遍历只是把节点数据入栈即可,这次我们需要涉及到括号 ,所以需要每次入栈的时候增加括号,按照先右括号 在左括号的方式入栈
3 唯一需要特殊处理的是 当左节点为空 但是右节点不为空的情况时候 需要入栈一个没有值的空括号

  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. type TreeNode struct {
  7. Val int
  8. Left *TreeNode
  9. Right *TreeNode
  10. }
  11. func tree2str(t *TreeNode) string {
  12. var str strings.Builder
  13. if t == nil {
  14. return ""
  15. }
  16. stack := []interface{}{t}
  17. for len(stack) > 0 {
  18. node := stack[len(stack)-1]
  19. stack = stack[:len(stack)-1]
  20. if n, ok := node.(*TreeNode); ok {
  21. str.WriteString(fmt.Sprintf("%d", n.Val))
  22. if n.Right != nil {
  23. stack = append(stack, ")")
  24. stack = append(stack, n.Right)
  25. stack = append(stack, "(")
  26. }
  27. if n.Right != nil && n.Left == nil {
  28. stack = append(stack, "()")
  29. }
  30. if n.Left != nil {
  31. stack = append(stack, ")")
  32. stack = append(stack, n.Left)
  33. stack = append(stack, "(")
  34. }
  35. } else {
  36. s := node.(string)
  37. str.WriteString(s)
  38. }
  39. }
  40. return str.String()
  41. }
  42. func main() {
  43. one := &TreeNode{Val: 1}
  44. two := &TreeNode{Val: 2}
  45. one.Left = two
  46. three := &TreeNode{Val: 3}
  47. one.Right = three
  48. four := &TreeNode{Val: 4}
  49. two.Right = four
  50. fmt.Println(tree2str(one))
  51. //one1 :=&TreeNode{Val: 1}
  52. //two1 :=&TreeNode{Val: 2}
  53. //one1.Left = two1
  54. //three1 :=&TreeNode{Val: 3}
  55. //one1.Right = three1
  56. //four1 :=&TreeNode{Val: 4}
  57. //two1.Right = four1
  58. //fmt.Println(tree2str(one1))
  59. }

image.png