Traversal Algorithms
In this lesson, you will learn how to traverse binary trees using a depth-first search.
We'll cover the following
Tree Traversal
Tree Traversal is the process of visiting (checking or updating) each node in a tree data structure, exactly once. Unlike linked lists or one-dimensional arrays that are canonically traversed in linear order, trees may be traversed in multiple ways. They may be traversed in depth-first or breadth-first order.
There are three common ways to traverse a tree in depth-first order:
- In-order
- Pre-order
- Post-order
Let’s begin with the Pre-order Traversal.
Pre-order Traversal
Here is the algorithm for a pre-order traversal:
- Check if the current node is empty/null.
- Display the data part of the root (or current node).
- Traverse the left subtree by recursively calling the pre-order method.
- Traverse the right subtree by recursively calling the pre-order method.
Get hands-on with 1400+ tech skills courses.