145.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 postorderTraversal(root *TreeNode) (nodes []int) {
  11. if root == nil {
  12. return
  13. }
  14. return postorderIteration(root)
  15. }
  16. func postorderRecurse(root *TreeNode, nodes *[]int) {
  17. if root == nil {
  18. return
  19. }
  20. postorderRecurse(root.Left, nodes)
  21. postorderRecurse(root.Right, nodes)
  22. *nodes = append(*nodes, root.Val)
  23. }
  24. func postorderIteration(root *TreeNode) (nodes []int) {
  25. stack := make([]*TreeNode, 0)
  26. for curr := root; ; {
  27. for curr != nil {
  28. if curr.Right != nil {
  29. stack = append(stack, curr.Right)
  30. }
  31. stack = append(stack, curr)
  32. curr = curr.Left
  33. } // Save right, root; visit left (the right node is saved to mark root.Right as unvisited)
  34. // curr is nil, pop top of stack
  35. curr = stack[len(stack)-1]
  36. stack = stack[:len(stack)-1]
  37. // If right is not visited, pop right, save root again, and visit right
  38. if curr.Right != nil && len(stack) != 0 && curr.Right == stack[len(stack)-1] {
  39. stack = stack[:len(stack)-1]
  40. stack = append(stack, curr)
  41. curr = curr.Right
  42. } else { // Else print root
  43. nodes = append(nodes, curr.Val)
  44. curr = nil
  45. }
  46. if len(stack) == 0 {
  47. break
  48. }
  49. }
  50. return
  51. }
  52. // func main() {
  53. // fmt.Println(postorderTraversal(
  54. // toBinaryTree(newInt(1), nil, newInt(2), newInt(3))))
  55. // }