Traversal
Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one logical way to traverse them, trees can be traversed in different ways. Following are the generally used ways for traversing trees.
Three common orders in BST traversal:
- Pre-order
- In-order
- Post-order
Pre-order Traversal
Visit (Node current){
if (current == null)
return;
Process(current.Value);
Visit(current.Left);
Visit(current.Right);
}
// result: 4 2 1 3 6 5 7
In-order Traversal
Visit (Node current){
if (current == null)
return;
Visit(current.Left);
Process(current.Value);
Visit(current.Right);
}
// result: 1 2 3 4 5 6 7
Post-order Traversal
Visit (Node current){
if (current == null)
return;
Visit(current.Left);
Visit(current.Right);
Process(current.Value);
}
// result: 1 3 2 5 7 6 4