

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 6
click for more info
Not enough gems
Cost: 6 gems
1: Trees
incomplete
2: Binary Trees
incomplete
3: Insert Nodes
incomplete
4: Insert Review
incomplete
5: Min and Max
incomplete
6: Delete
incomplete
7: Deletion Review
incomplete
8: Preorder Traversal
incomplete
9: Postorder Traversal
incomplete
10: Inorder Traversal
incomplete
11: Node Exists
incomplete
12: Height
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
A "preorder" traversal is a way to visit all the nodes in a tree. It's called "preorder" because the current node is visited before its children. This tree:
Would be traversed in this order:
[5, 3, 2, 8, 7, 10, 9, 12]
Interactive example available with JavaScript enabled.
Sometimes it's useful (albeit a bit slow) to iterate over all the nodes in the tree. In the case of LockedIn, we've been asked to build a way to create a backup of our database indexes - this traversal will allow us to save all the data in the tree to a file.
Implement the recursive preorder method. It returns a list of the values in the order they are visited, and it takes as an argument the ordering of values we have visited so far.
For example, the first call to preorder on an entire tree would be:
# an empty list is passed in the first call
bst_node.preorder([])
Here are the algorithm's steps: