bfs and dfs

22
BFS & DFS

Upload: rajendranbehappy

Post on 15-Sep-2015

220 views

Category:

Documents


5 download

DESCRIPTION

BFS and DFS

TRANSCRIPT

  • BFS & DFS

  • Outline

    Breadth-first traversal

    Depth-first traversal

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

    order

    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 level-

    order traversalBreadth-first Traversal:

    A,B,C,D,E,F,G,H,I

    A

    B C

    F GD E

    H I

  • Breadth-first traversal (2)

    General strategy: use a queue to keep track of the order of nodes

    Pseudocode:

    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

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

  • 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 firstDepth-first Traversal:

    A,C,G,F,B,E,I,H,D

    or

    A,B,D,E,H,I,C,F,G

    A

    B C

    F GD E

    H I

  • Depth-first traversal (2)

    General strategy: use a stack to keep track of the order of nodes

    Pseudocode:

    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

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

  • Visualizations

    BFT DFT

    BFT gif: http://en.wikipedia.org/wiki/Breadth-

    first_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: Nonevisit(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

    A

    B C

    F GD E

    H I

    Note: this is similar to iterative DFT

  • Post-order traversal

    function postorder(node)://Input: root node of tree//Output: Noneif node has left child

    postorder(node.left)if node has right child

    postorder(node.right)visit(node)

    A

    B C

    F GD E

    H I

    Post-order Traversal:

    D,H,I,E,B,F,G,C,A

  • In-order traversal

    function inorder(node)://Input: root node of tree//Output: Noneif 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

    A

    B C

    F GD E

    H I

  • Visualizations

    Pre-Order

    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

    Think of the

    prefix as when

    the root is visited!

  • 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

    B

    L R

  • 10

    5

    Euler Traversal Pseudocode

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

    visitLeft(node) // Pre-order

    if node has left child:eulerTour(node.left)

    visitBelow(node) // In-order

    if node has right child:eulerTour(node.right)

    visitRight(node) // Post-order

    1

    2

    3

    4

    6

    7

    8

    9

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27A

    B C

    F GD E

    H I

  • 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

    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?

    +

    - /

    9 37 +

    4 3

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

  • Practice Problem 4

    Given an arithmetic expression tree, print out the expression, without parentheses

    Best traversal: in-order

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

    7 4 + 3 + 9 / 3

    +

    - /

    9 37 +

    4 3

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

    expression, with parentheses

    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

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

    +

    - /

    9 37 +

    4 3