Def: Tree Traversal
- the process of visiting/examining/updating each node in a tree data structure
- there are multiple ways to traverse a tree
root -> left subtree -> right subtree
def preorder
Things to Note:
- Start from the top and go down
- You hit everything in your path
- Go all the way down the left and then you can start on the ones on the right that you didn't get
Analogy: kind of like when you're getting your 8 gym badges, very linear, you go forward not back
Code:
def preorder(tl: 'TreeList') -> list:
return [] if tl is None else ([tl[0]]\
+ preorder(tl[1]) + preorder(tl[2]))
2. In-Order:
left subtree -> root -> right subtree
Things to Note:
- Start at the bottom most left
- Always visit "root" after the left child but before you go to the right child
- If there is no left child go straight to root
Code:
def inorder(tl: 'TreeList') -> list:
return [] if tl is None else inorder(tl[1])\
+ [tl[0]] + inorder(tl[2])
3. Post-Order:
left subtree -> right subtree -> root
Things to Note:
- Start at the most left
- The main root will be your last hit
Code:
def postorder(tl: 'TreeList') -> list:
return [] if tl is None else postorder(tl[1])\ + postorder(tl[2]) + [tl[0]]
And that concludes 2 AM blogging and the plethora of bad Pokemon analogies.


