You are on page 1of 22

BFS & DFS

Outline
Breadth-first traversal
Depth-first traversal

Recursive DFT: pre-order, post-order, inorder


Euler Tour traversal
Practice problems

Tree Traversals
Unlike an array, its not always obvious how

to visit every element stored in a tree


A tree traversal is an algorithm for visiting
every node in a tree
There are many possible tree traversals
that visit the nodes in different orders

Breadth-first traversal
Starting from the root

node, visit both of its


children first, then all of
its grandchildren, then
great-grandchildren
etc
Also known as levelorder traversal

Breadth-first Traversal:
A,B,C,D,E,F,G,H,I

Breadth-first traversal (2)


General strategy: use a queue to keep track of the

order of nodes
Pseudocode:
function bft(root):
//Input: root node of tree
//Output: None
Q = new Queue()
enqueue root
while Q is not empty:
node = Q.dequeue()
visit(node)
enqueue nodes left & right children

The queue guarantees that all the nodes of a given

level are visited before any of their children are visited


Can enqueue nodes left and right children in any order

Depth-first traversal
Starting from the root

node, explore each


branch as far as
possible before
backtracking
This can still produce
many different orders,
depending on which
branch you visit first

Depth-first Traversal:
A,C,G,F,B,E,I,H,D
or
A,B,D,E,H,I,C,F,G

Depth-first traversal (2)


General strategy: use a stack to keep track of the

order of nodes
Pseudocode:
function dft(root):
//Input: root node of tree
//Output: none
S = new Stack()
push root onto S
while S is not empty:
node = S.pop()
visit(node)
push nodes left and right children

The stack guarantees that you explore a branch all

the way to a leaf before exploring another


Can add children to stack in any order

Visualizations
BFT

DFT

BFT gif: http://en.wikipedia.org/wiki/Breadthfirst_search#mediaviewer/File:Animated_BFS.gif


DFT gif:
https://upload.wikimedia.org/wikipedia/commons/7/7f/Depth-First-Search.gif

Recursive Depth-First Traversals


We can also implement DFT recursively!
Using recursion, we can end up with 3

different orders of nodes, depending on our


implementation
Pre-order visits each node before visiting its

left and right children


Post-order visits each node after visiting its
left and right children
In-order visits the nodes left child, itself, and
then its right child

Pre-order traversal
function preorder(node):
//Input: root node of tree
//Output: None
visit(node)
if node has left child
preorder(node.left)
if node has right child
preorder(node.right)

Pre-order Traversal:
A,B,D,E,H,I,C,F,G
Note: this is similar to iterative DFT

Post-order traversal
function postorder(node):
//Input: root node of tree
//Output: None
if node has left child
postorder(node.left)
if node has right child
postorder(node.right)
visit(node)

Post-order Traversal:
D,H,I,E,B,F,G,C,A

In-order traversal
function inorder(node):
//Input: root node of tree
//Output: None
if node has left child
inorder(node.left)
visit(node)
if node has right child
inorder(node.right)

In-order Traversal:
D,B,H,E,I,A,F,C,G

Visualizations
Pre-Order

Think of the
prefix as when
the root is visited!

In-order

Post-order
Preorder gif: http://ceadserv1.nku.edu/longa//classes/mat385_resources/docs/traversal_files/PreOrderTrav.gif
Inorder gif: http://ceadserv1.nku.edu/longa//classes/mat385_resources/docs/traversal_files/InorderTrav.gif
Postorder gif: http://ceadserv1.nku.edu/longa//classes/mat385_resources/docs/traversal_files/PostorderTrav.gif

Euler Tour Traversal


Generic traversal of a

binary tree
Includes as special
cases the pre-order,
post-order, and in-order
traversals
Walk around the tree
and visit each node
three times:
On the left (pre-order)
From below (in-order)
On the right (post-order)

Creates subtrees for all

nodes

Euler Traversal Pseudocode


function eulerTour(node):
// Input: root node of tree
// Output: None

27

17

visitLeft(node) // Pre-order

if node has left child:


eulerTour(node.left)

if node has right child:


eulerTour(node.right)
visitRight(node) // Post-order

15

H 10 12 I
9

19

20

11

26

22

6
3

visitBelow(node) // In-order

18

16

13

14

21 23 G
24

25

Aside: Decoration
Often youll be asked to decorate each

node in a tree with some value


Decorating a node just means associating
a value to it. There are two conventional
ways to do this:
Add a new attribute to each node
e.g. node.numDescendants = 5

Maintain a dictionary that maps each node to its

decoration do this if you dont want to or cant


modify the original tree
e.g. descendantDict[node] = 5

When do I use what traversal?


With so many tree traversals in your

arsenal, how do you know which one to


use?
Sometimes it doesnt matter, but often there
will be one traversal that makes solving a
problem much easier

Practice Problem 1
Decorate each node with the number of its

descendants
Best traversal: post-order
Its easy to calculate the number descendants
of a node if you already know how many
descendants each of its children has
Since post-order traversal visits both children
before the parent, this is the traversal we want
Try writing some pseudocode for this!

Practice Problem 2
Given the root of a tree, determine if the tree

is perfect
Best traversal: breadth-first
This problem is easiest solved by traversing the
tree level-by-level
We can keep track of the current level, and at each
level count the number of nodes we see
Each level should have exactly twice as many
nodes as the last
There are other ways to solve this problem too can you think of any?

Practice Problem 3
Given an arithmetic expression tree, evaluate the

expression
+
/

(7 (4 + 3)) + (9 / 3)
7

+
4

Best traversal: post-order


In order to evaluate an arithmetic operation, you first
need to evaluate the sub-expression on each side
What should you do when you get to a leaf?

Practice Problem 4
Given an arithmetic expression tree, print

out the expression, without parentheses


+
-

74+3+9/3
7

+
4

Best traversal: in-order


in-order traversals gives you the nodes from left
to right, which is exactly the order we want!

Practice Problem 5
Given an arithmetic expression tree, print out the

expression, with parentheses


+
-

+
4

((7 (4 + 3)) + (9 / 3))


3

Best traversal: Euler tour


If the nodes is an internal node (i.e. an operator):
For the pre-order visit, print out (
For the in-order visit, print out the operator
For the post-order visit, print out )

If the node is a leaf (i.e. a number):


Dont do anything for pre-order and post-order visits
For the in-order visit, print out the number

You might also like