94.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package main
  2. /**
  3. * Definition for a binary tree node.
  4. * type TreeNode struct {
  5. * Val int
  6. * Left *TreeNode
  7. * Right *TreeNode
  8. * }
  9. */
  10. func inorderTraversal(root *TreeNode) []int {
  11. result := []int{}
  12. if root == nil {
  13. return result
  14. }
  15. inorderTraversalHelper(root, &result)
  16. return result
  17. }
  18. func inorderTraversalHelper(root *TreeNode, result *[]int) {
  19. if root.Left != nil {
  20. inorderTraversalHelper(root.Left, result)
  21. }
  22. *result = append(*result, root.Val)
  23. if root.Right != nil {
  24. inorderTraversalHelper(root.Right, result)
  25. }
  26. }
  27. func inorderTraversalIter(root *TreeNode) []int {
  28. result := []int{}
  29. stack := []*TreeNode{}
  30. curr := root
  31. top := -1
  32. for curr != nil || top > -1 {
  33. for curr != nil {
  34. // push
  35. stack = append(stack, curr)
  36. top++
  37. curr = curr.Left
  38. }
  39. if top > -1 {
  40. curr = stack[top]
  41. // pop
  42. stack = stack[:top]
  43. top--
  44. result = append(result, curr.Val)
  45. curr = curr.Right
  46. }
  47. }
  48. return result
  49. }
  50. // func main() {
  51. // // 1
  52. // // /
  53. // // 2
  54. // // / \
  55. // // 3 nil
  56. // n3 := TreeNode{3, nil, nil}
  57. // n2 := TreeNode{2, &n3, nil}
  58. // n1 := TreeNode{1, &n2, nil}
  59. // fmt.Println(inorderTraversalIter(&n1))
  60. // }