Elementsa re visited in a FIFO system, all nodes are visited before next
Using Stack
Implementation
1
2
3
4
5
6
7
8
9
10
PreOrder(root):
s = create stack of nodes
s.push(root)
While s is not empty:
node = s.pop()
printf(node→value)
if (node→right != NULL)
s.push(node→right)
if (node→left != NULL)
s.push(node→left)
Traversal
On graph:
Using Queue
Prints layer by layer, as the child nodes get sent to the back
Implementation
1
2
3
4
5
6
7
8
9
10
BreadthFirstSearch(root):
q = create queue of nodes
q.enqueue(root)
while q is not empty:
node = q.dequeue()
printf(node→value)
if (node→left != NULL)
q.enqueue(node→left)
if (node→right != NULL)
q.enqueue(node→right)