Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
• BreadthFirst traversal
• DepthFirst traversal
1
Tree Traversal (Definition)
• The process of systematically visiting all the nodes in a tree and
performing some computation at each node in the tree is called a
tree traversal.
2
Breadth-First Traversal
• The BinaryTree class breadthFirstTraversal method:
3
Breadth-First Traversal
D L
B F J N
A C E G I K M O
O M K I G E C A N J F B L D H
4
Depth-First Traversals
N-L-R
H
D L
B F J N
A C E G I K M O
O M N K I J L G E F C A B D H
6
Depth-first Inorder Traversal
L-N-R
H
D L
B F J N
A C E G I K M O
O N M L K J I H G F E D C B A
.Note: An inorder traversal of a BST visits the keys sorted in increasing order
7
Depth-first Postorder Traversal
L-R-N
H
D L
B F J N
A C E G I K M O
H L N O M J K I D F G E B C A
8
Traversals
9
The accept method of the BinaryTree class
10
Binary Tree Iterator
• The BinaryTree class provides a tree iterator that does a preorder
traversal. The iterator is implemented as an inner class:
public BinaryTreeIterator(){
stack = new StackAsLinkedList();
if(!isEmpty())stack.push(BinaryTree.this);
}