What is graph traversal?
The process of systematically visiting each node in a graph.
What is breadth first traversal?
Nodes closest to the start node are visited first.
E.g. finding the shortest path through an unweighted graph (Dijkstra).
What is depth first traversal?
Exploring as far as possible away from the start node.
E.g. solving puzzles like mazes.
What is the time complexity of tree traversals?
O(n) because every node is visited once.
What are the three types of tree traversal?
Pre-order, in-order and post-order.
All tree traversals are depth first traversals.
Explain pre-order traversal.
Pattern: visit, left, right
Use: copying a tree
In pre-order traversals, the node is visited before traversing its left and right subtrees.
That’s why the root is the first node outputted.
Explain in-order traversal.
They are used for binary search trees only.
Pattern: left, visit, right
Use: outputting a binary search tree in ascending order
In-order traversals will output the contents of a binary search tree in order. It only outputs the node once all the nodes on its left have been output.
Explain post-order traversal.
Pattern: left, right, visit
Use: converting infix to RPN (RPN is post-fix)
Post-order only outputs the node once it has output all the nodes on its left and right. The root is the last node to be output/visited.