Group Group Group Group Group Group Group Group Group

Chapter 12.2 Binary tree traversal algorithms

It hard for me how to memorize the difference between each traversal algorithms… until I see the code side-by-side in the playground:

public func traversePreOrder(visit: (Element) -> Void) {
  leftChild?.traversePreOrder(visit: visit)
  rightChild?.traversePreOrder(visit: visit)

public func traverseInOrder(visit: (Element) -> Void) {
  leftChild?.traverseInOrder(visit: visit)
  rightChild?.traverseInOrder(visit: visit)

public func traversePostOrder(visit: (Element) -> Void) {
  leftChild?.traversePostOrder(visit: visit)
  rightChild?.traversePostOrder(visit: visit)

pre-order, visit() at front
in-order, visit() in middle
post-order, visit() at back

It’s like a eureka moment for me. I could easily create a mental model for all the types of traversals. I wish the book, although already very near, has a side-by-side view of the code like this.

Thank you for sharing this @hlung! Being a visual learner I too enjoy looking at side by side comparisons.