Trees and traversals
A tree links a parent to its children. A rooted tree has one path from the root to each node. Traversal is the order in which you visit them.
Simple example
Node 2 has left child 1 and right child 3. For an inorder walk, visit the left child, then its parent, then the right child.
object Lesson {
def main(args: Array[String]): Unit = {
var keys = Array(2, 1, 3)
var left = Array(1, -1, -1)
var right = Array(2, -1, -1)
var stack = Array(0, 0, 0)
var size = 0
var node = 0
while ((node != -1) || (size > 0)) {
while (node != -1) {
stack(size) = node
size += 1
node = left(node)
}
size -= 1
node = stack(size)
println(keys(node))
node = right(node)
}
}
}
1 2 3
Everyday examples
List folders before their contents
Folder A holds folders B and C. List each folder before visiting its children, left to right. What order appears?
A preorder walk lists A first, then the contents of B, then the contents of C.
Pack smaller boxes first
Box A contains boxes B and C. Each inner box must be sealed before its outer box. When can A be sealed?
A postorder walk finishes both children before the parent. A is sealed last.
Announce a club by level
Chair A leads captains B and C. B leads D. Which announcement order reaches the captains before the member?
Visit one level at a time. A queue keeps D waiting until both captains have been announced.
Cost and limits
Visiting every node takes linear time. An inorder walk sorts values only when the tree also follows the binary search tree ordering rule.