Check-in Exercise #
Trees. A tree consists of a set of nodes and a set of edges connecting the nodes, where there is only one path between any two nodes. A tree is thus a graph with no cycles and all vertices connected.
Traversals. When we iterate over a tree, we call this a “tree traversal”.
Level Order Traversal. A level-order traversal visits every item at level 0, then level 1, then level 2, and so forth.
Depth First Traversals. We have three depth first traversals: Pre-order, in-order and post-order. In a pre-order traversal, we visit a node, then traverse its children. In an in-order traversal, we traverse the left child, visit a node, then traverse the right child. In a post-order traversal, we traverse both children before visiting. These are very natural to implement recursively. Pre-order and post-order generalize naturally to trees with arbtirary numbers of children. In-order only makes sense for binary trees.
Graphs. A graph consists of a set of nodes and a set of edges connecting the nodes. However, unlike our tree definition, we can have more than one path between nodes. Note that all trees are graphs. In CS 61B, we can assume all graphs are simple graphs (AKA no loops or parallel edges).
Depth First Traversals. DFS for graphs is similar to DFS for trees, but since there are potential cycles within our graph, we add the constraint that each vertex should be visited at most once. This can be accomplished by marking nodes as visited and only visiting a node if it had not been marked as visited already.
Recommended Problems #
C level #
- Question 1 from the Fall 2014 discussion worksheet.
B level #
- Question 4 from the Fall 2014 midterm.
A level #
- Question 7 from the guerrilla section worksheet #2 from Spring 2015.