Depth-first search
Here we present depth-first search using pre-order, post-order and in-order traversal.
We don’t go over code in the videos, though we do supply pseudocode. However, we do include complete source code for implementation of DFS (all traversal methods) and BFS here for your review. These follow very closely the pseudocode provided in the videos and slides.
Depth-first search with pre-order traversal (8:10)
Depth-first search with post-order traversal and in-order traversal (12:27)
Here’s a question: What’s the worst case time complexity for depth-first search? Consider this graph:
What’s the problem here? Clearly complexity is at least of order \mathcal{O}(N) (where N is the number of nodes/vertices). But for each vertex we must scan for adjacent nodes. If we were using an adjacency matrix, this would be of order \mathcal{O}(N^2). Using a adjacency list this becomes \mathcal{O}(N + E) where E is the number of edges. So we’ll call it \mathcal{O}(N + E) , since we can choose an appropriate data structure.
Resources
Additional reading
Comprehension check:
- Which of the following records a node as having been visited as soon as it is encountered?
- pre-order traversal
- in-order traversal
- post-order traversal
- True or false? Post-order traversal has greater run-time complexity than pre-order traversal.
Answers: ǝslɐɟ / ɹǝpɹo-ǝɹd
Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >
No generative AI was used in producing this material. This was written the old-fashioned way.
All materials copyright © 2020–2023, The University of Vermont. All rights reserved.