SlideShare una empresa de Scribd logo
1 de 16
Tree Walks/Traversals

 A tree  walk or traversal is a way of visiting
  all the nodes in a tree in a specified order.
 A preorder tree walk processes each node
  before processing its children
 A postorder tree walk processes each
  node after processing its children


                                                   1
Traversing Trees (preorder)




   preorder traversal
    Algorithm preOrder(v)
      “visit” node v
      for each child w of v do
        recursively perform preOrder(w)
   reading a document from beginning to end

                                               2
Traversing Trees (postorder)




   postorder traversal
    Algorithm postOrder(v)
      for each child w of v do
      recursively perform postOrder(w)
      “visit” node v
   du (disk usage) command in Unix
                                         3
Traversals of Binary Trees
preorder(v)
  if (v == null) then return
  else visit(v)
         preorder(v.leftchild())
         preorder(v.rightchild())

 postorder(v)
  if (v == null) then return
  else postorder(v.leftchild())
         postorder(v.rightchild())
         visit(v)
                                     4
Examples of pre and postorder
                                       a
  We  assume that we
   are only printing the           b       e
   data in a node when
                                       d
   we visit it.                c

 Preorder       Postorder          f
                                           g

a b c d f g e   c f g d be a



                                               5
Evaluating Arithmetic Expressions
   specialization of a
    postorder traversal




Algorithm evaluate(v)
     if v is a leaf
           return the variable stored at v
     else
           let o be the operator stored at v
           x     evaluate(v.leftChild())
           y     evaluate(v.rightChild())
           return x o y                        6
Traversing Trees
   Besides preorder and postorder, a third
    possibility arises when v is visted between the
    visit to the left ad right subtree.

   Algorithm inOrder(v)
     if (v == null) then return
     else inOrder(v.leftChild())
           visit(v)
           inOrder(v.rightChild())



                                                      7
Inorder Example
                          a
 Inorder
                      b       e
  c b f d ga e
                  c       d

                              g
                      f




                                  8
Euler Tour Traversal
   generic traversal of a binary tree
   the preorder, inorder, and postorder traversals are special
    cases of the Euler tour traversal
   “walk around” the tree and visit each node three times:
       on the left
       from below
       on the right




                                                              9
Printing an arithmetic expression
   Printing an arithmetic
    expression - so called
    Euler’s walk:
     Print “(“ before
      traversing the left
      subtree, traverse it
     Print the value of a
      node
     Traverse the right
      subtree, print “)” after
      traversing it
                                    10
Template Method Pattern
   generic computation
    mechanism that can be
    specialized by redefining
    certain steps
   implemented by means of
    an abstract Java class
    with methods that can be
    redefined by its
    subclasses




                                11
Specializing Generic Binary Tree Traversal
    printing an arithmetic expression
     public class PrintExpressionTraversal extends
     BinaryTreeTraversal {
     ...
     protected void external(Position p, TraversalResult r)
         { System.out.print(p.element()); }
     protected void left(Position p, TraversalResult r)
         { System.out.print("("); }
     protected void below(Position p, TraversalResult r)
         { System.out.print(p.element()); }
     protected void right(Position p, TraversalResult r)
         { System.out.print(")"); }
     }                                                        12
Building tree from pre- and in- order
 Given the preorder and
  inorder traversals of a binary           a
  tree we can uniquely
  determine the tree.                  b       e
Preorder              Inorder
                                   c       d
abcdfge         cbfdgae
                                               g
                                       f
    bcdfg       cbfdg

     d f g         f d g


                                                   13
Building tree from post and inorder
 In place of preorder we can use postorder.
 The last node visited in the postorder
  traversal is the root of the binary tree.
 This can then be used to split in the
  inorder traversal to identify the left and
  right subtrees.
 Procedure is similar to the one for
  obtaining tree from preorder and inorder
  traversals.

                                           14
Insufficiency of pre & postorder
 Given  the pre and postoder traversal of a
  binary tree we cannot uniquely identify the
  tree.
 This is because there can be two trees
  with the same pre and postorder
  traversals.
                              a      a
    Preorder: a b c
                          b              b
    Postorder: c b a
                              c      c

                                                15
A special case
 If each internal node of the
  binary tree has at least two
                                          a
  children then the tree can
  be determined from the pre          b       e
  and post order traversals.
Preorder              postorder   c       d

                                              g
abcdfge           cfgdbea             f


    bcdfg         cfgdb

      d f g         f g d
                                                  16

Más contenido relacionado

La actualidad más candente

Cours algorithmique et complexite complet
Cours algorithmique et complexite completCours algorithmique et complexite complet
Cours algorithmique et complexite completChahrawoods Dmz
 
Les algorithmes d'arithmetique
Les algorithmes d'arithmetiqueLes algorithmes d'arithmetique
Les algorithmes d'arithmetiquemohamed_SAYARI
 
Chapitre iii récursivité et paradigme diviser pour régner
Chapitre iii récursivité et paradigme diviser pour régnerChapitre iii récursivité et paradigme diviser pour régner
Chapitre iii récursivité et paradigme diviser pour régnerSana Aroussi
 
Sommation séries entières
Sommation séries entièresSommation séries entières
Sommation séries entièresLoïc Dilly
 
Chap04 les-algorithme-de-tri-et-de-recherche
Chap04 les-algorithme-de-tri-et-de-rechercheChap04 les-algorithme-de-tri-et-de-recherche
Chap04 les-algorithme-de-tri-et-de-rechercheRiadh Harizi
 
Chapitre iv algorithmes de tri
Chapitre iv algorithmes de triChapitre iv algorithmes de tri
Chapitre iv algorithmes de triSana Aroussi
 
Notes DATA STRUCTURE - queue
Notes DATA STRUCTURE - queueNotes DATA STRUCTURE - queue
Notes DATA STRUCTURE - queueFarhanum Aziera
 
Chapitre 2 -Complexité des problèmes avec correction.pdf
Chapitre 2 -Complexité des problèmes avec correction.pdfChapitre 2 -Complexité des problèmes avec correction.pdf
Chapitre 2 -Complexité des problèmes avec correction.pdfMbarkiIsraa
 
Insertion in singly linked list
Insertion in singly linked listInsertion in singly linked list
Insertion in singly linked listKeval Bhogayata
 

La actualidad más candente (20)

Lec3
Lec3Lec3
Lec3
 
Lec20
Lec20Lec20
Lec20
 
Lec1
Lec1Lec1
Lec1
 
Lec3
Lec3Lec3
Lec3
 
Lec11
Lec11Lec11
Lec11
 
Lec5
Lec5Lec5
Lec5
 
Cours algorithmique et complexite complet
Cours algorithmique et complexite completCours algorithmique et complexite complet
Cours algorithmique et complexite complet
 
Les algorithmes d'arithmetique
Les algorithmes d'arithmetiqueLes algorithmes d'arithmetique
Les algorithmes d'arithmetique
 
Algorithmes de tri
Algorithmes de triAlgorithmes de tri
Algorithmes de tri
 
Chapitre iii récursivité et paradigme diviser pour régner
Chapitre iii récursivité et paradigme diviser pour régnerChapitre iii récursivité et paradigme diviser pour régner
Chapitre iii récursivité et paradigme diviser pour régner
 
Recursiviteeeeeeeeee
RecursiviteeeeeeeeeeRecursiviteeeeeeeeee
Recursiviteeeeeeeeee
 
Récursivité
RécursivitéRécursivité
Récursivité
 
Sommation séries entières
Sommation séries entièresSommation séries entières
Sommation séries entières
 
Chap04 les-algorithme-de-tri-et-de-recherche
Chap04 les-algorithme-de-tri-et-de-rechercheChap04 les-algorithme-de-tri-et-de-recherche
Chap04 les-algorithme-de-tri-et-de-recherche
 
Chapitre iv algorithmes de tri
Chapitre iv algorithmes de triChapitre iv algorithmes de tri
Chapitre iv algorithmes de tri
 
Linked list
Linked list Linked list
Linked list
 
Notes DATA STRUCTURE - queue
Notes DATA STRUCTURE - queueNotes DATA STRUCTURE - queue
Notes DATA STRUCTURE - queue
 
Linked list
Linked listLinked list
Linked list
 
Chapitre 2 -Complexité des problèmes avec correction.pdf
Chapitre 2 -Complexité des problèmes avec correction.pdfChapitre 2 -Complexité des problèmes avec correction.pdf
Chapitre 2 -Complexité des problèmes avec correction.pdf
 
Insertion in singly linked list
Insertion in singly linked listInsertion in singly linked list
Insertion in singly linked list
 

Destacado

Tree Traversals (In-order, Pre-order and Post-order)
Tree Traversals (In-order, Pre-order and Post-order)Tree Traversals (In-order, Pre-order and Post-order)
Tree Traversals (In-order, Pre-order and Post-order)raj upadhyay
 
Linear Search Data Structure
Linear Search Data StructureLinear Search Data Structure
Linear Search Data StructureTalha Shaikh
 
기업교육론 6장 학생발표자료
기업교육론 6장 학생발표자료기업교육론 6장 학생발표자료
기업교육론 6장 학생발표자료조현경
 
삼성핵심가치위반사례
삼성핵심가치위반사례삼성핵심가치위반사례
삼성핵심가치위반사례조현경
 
Say Hello To Illinois - WiP
Say Hello To Illinois - WiPSay Hello To Illinois - WiP
Say Hello To Illinois - WiPSoreh
 
Trial slideshow
Trial slideshowTrial slideshow
Trial slideshowkilaht805
 
10강 기업교육론 20110504
10강 기업교육론 2011050410강 기업교육론 20110504
10강 기업교육론 20110504조현경
 
Cost Reductions Process - Results
Cost Reductions Process - ResultsCost Reductions Process - Results
Cost Reductions Process - Resultsoferyuval
 
Intro computer
Intro computerIntro computer
Intro computerprajug2503
 
Hieu qua san xuat bap lai tren dat lua dbscl
Hieu qua san  xuat bap lai tren dat lua dbsclHieu qua san  xuat bap lai tren dat lua dbscl
Hieu qua san xuat bap lai tren dat lua dbsclHo Cao Viet
 
Learning from Web Activity
Learning from Web ActivityLearning from Web Activity
Learning from Web Activityjakehofman
 
οι κήποι του ζAhrady
οι κήποι του ζAhradyοι κήποι του ζAhrady
οι κήποι του ζAhradyfilipj2000
 

Destacado (20)

Lec13
Lec13Lec13
Lec13
 
Tree Traversals (In-order, Pre-order and Post-order)
Tree Traversals (In-order, Pre-order and Post-order)Tree Traversals (In-order, Pre-order and Post-order)
Tree Traversals (In-order, Pre-order and Post-order)
 
Basic data-structures-v.1.1
Basic data-structures-v.1.1Basic data-structures-v.1.1
Basic data-structures-v.1.1
 
4.4 hashing
4.4 hashing4.4 hashing
4.4 hashing
 
Linear Search Data Structure
Linear Search Data StructureLinear Search Data Structure
Linear Search Data Structure
 
The bestof
The bestofThe bestof
The bestof
 
기업교육론 6장 학생발표자료
기업교육론 6장 학생발표자료기업교육론 6장 학생발표자료
기업교육론 6장 학생발표자료
 
삼성핵심가치위반사례
삼성핵심가치위반사례삼성핵심가치위반사례
삼성핵심가치위반사례
 
Canaima
CanaimaCanaima
Canaima
 
Gettysburg
GettysburgGettysburg
Gettysburg
 
Say Hello To Illinois - WiP
Say Hello To Illinois - WiPSay Hello To Illinois - WiP
Say Hello To Illinois - WiP
 
Trial slideshow
Trial slideshowTrial slideshow
Trial slideshow
 
Madrid `in tanitimi
Madrid `in tanitimiMadrid `in tanitimi
Madrid `in tanitimi
 
10강 기업교육론 20110504
10강 기업교육론 2011050410강 기업교육론 20110504
10강 기업교육론 20110504
 
Cost Reductions Process - Results
Cost Reductions Process - ResultsCost Reductions Process - Results
Cost Reductions Process - Results
 
Intro computer
Intro computerIntro computer
Intro computer
 
Presentatie carrieredagen 2011 linkedin
Presentatie carrieredagen 2011 linkedinPresentatie carrieredagen 2011 linkedin
Presentatie carrieredagen 2011 linkedin
 
Hieu qua san xuat bap lai tren dat lua dbscl
Hieu qua san  xuat bap lai tren dat lua dbsclHieu qua san  xuat bap lai tren dat lua dbscl
Hieu qua san xuat bap lai tren dat lua dbscl
 
Learning from Web Activity
Learning from Web ActivityLearning from Web Activity
Learning from Web Activity
 
οι κήποι του ζAhrady
οι κήποι του ζAhradyοι κήποι του ζAhrady
οι κήποι του ζAhrady
 

Similar a Lec7

Breath first Search and Depth first search
Breath first Search and Depth first searchBreath first Search and Depth first search
Breath first Search and Depth first searchKirti Verma
 
Skiena algorithm 2007 lecture12 topological sort connectivity
Skiena algorithm 2007 lecture12 topological sort connectivitySkiena algorithm 2007 lecture12 topological sort connectivity
Skiena algorithm 2007 lecture12 topological sort connectivityzukun
 
09 binary-trees
09 binary-trees09 binary-trees
09 binary-treesTech_MX
 
Trees - Non Linear Data Structure
Trees - Non Linear Data StructureTrees - Non Linear Data Structure
Trees - Non Linear Data StructurePriyanka Rana
 

Similar a Lec7 (6)

Lec7
Lec7Lec7
Lec7
 
Binary Tree Traversal
Binary Tree TraversalBinary Tree Traversal
Binary Tree Traversal
 
Breath first Search and Depth first search
Breath first Search and Depth first searchBreath first Search and Depth first search
Breath first Search and Depth first search
 
Skiena algorithm 2007 lecture12 topological sort connectivity
Skiena algorithm 2007 lecture12 topological sort connectivitySkiena algorithm 2007 lecture12 topological sort connectivity
Skiena algorithm 2007 lecture12 topological sort connectivity
 
09 binary-trees
09 binary-trees09 binary-trees
09 binary-trees
 
Trees - Non Linear Data Structure
Trees - Non Linear Data StructureTrees - Non Linear Data Structure
Trees - Non Linear Data Structure
 

Lec7

  • 1. Tree Walks/Traversals  A tree walk or traversal is a way of visiting all the nodes in a tree in a specified order.  A preorder tree walk processes each node before processing its children  A postorder tree walk processes each node after processing its children 1
  • 2. Traversing Trees (preorder)  preorder traversal Algorithm preOrder(v) “visit” node v for each child w of v do recursively perform preOrder(w)  reading a document from beginning to end 2
  • 3. Traversing Trees (postorder)  postorder traversal Algorithm postOrder(v) for each child w of v do recursively perform postOrder(w) “visit” node v  du (disk usage) command in Unix 3
  • 4. Traversals of Binary Trees preorder(v) if (v == null) then return else visit(v) preorder(v.leftchild()) preorder(v.rightchild()) postorder(v) if (v == null) then return else postorder(v.leftchild()) postorder(v.rightchild()) visit(v) 4
  • 5. Examples of pre and postorder a  We assume that we are only printing the b e data in a node when d we visit it. c Preorder Postorder f g a b c d f g e c f g d be a 5
  • 6. Evaluating Arithmetic Expressions  specialization of a postorder traversal Algorithm evaluate(v) if v is a leaf return the variable stored at v else let o be the operator stored at v x evaluate(v.leftChild()) y evaluate(v.rightChild()) return x o y 6
  • 7. Traversing Trees  Besides preorder and postorder, a third possibility arises when v is visted between the visit to the left ad right subtree.  Algorithm inOrder(v) if (v == null) then return else inOrder(v.leftChild()) visit(v) inOrder(v.rightChild()) 7
  • 8. Inorder Example a  Inorder b e c b f d ga e c d g f 8
  • 9. Euler Tour Traversal  generic traversal of a binary tree  the preorder, inorder, and postorder traversals are special cases of the Euler tour traversal  “walk around” the tree and visit each node three times:  on the left  from below  on the right 9
  • 10. Printing an arithmetic expression  Printing an arithmetic expression - so called Euler’s walk:  Print “(“ before traversing the left subtree, traverse it  Print the value of a node  Traverse the right subtree, print “)” after traversing it 10
  • 11. Template Method Pattern  generic computation mechanism that can be specialized by redefining certain steps  implemented by means of an abstract Java class with methods that can be redefined by its subclasses 11
  • 12. Specializing Generic Binary Tree Traversal  printing an arithmetic expression public class PrintExpressionTraversal extends BinaryTreeTraversal { ... protected void external(Position p, TraversalResult r) { System.out.print(p.element()); } protected void left(Position p, TraversalResult r) { System.out.print("("); } protected void below(Position p, TraversalResult r) { System.out.print(p.element()); } protected void right(Position p, TraversalResult r) { System.out.print(")"); } } 12
  • 13. Building tree from pre- and in- order  Given the preorder and inorder traversals of a binary a tree we can uniquely determine the tree. b e Preorder Inorder c d abcdfge cbfdgae g f bcdfg cbfdg d f g f d g 13
  • 14. Building tree from post and inorder  In place of preorder we can use postorder.  The last node visited in the postorder traversal is the root of the binary tree.  This can then be used to split in the inorder traversal to identify the left and right subtrees.  Procedure is similar to the one for obtaining tree from preorder and inorder traversals. 14
  • 15. Insufficiency of pre & postorder  Given the pre and postoder traversal of a binary tree we cannot uniquely identify the tree.  This is because there can be two trees with the same pre and postorder traversals. a a Preorder: a b c b b Postorder: c b a c c 15
  • 16. A special case  If each internal node of the binary tree has at least two a children then the tree can be determined from the pre b e and post order traversals. Preorder postorder c d g abcdfge cfgdbea f bcdfg cfgdb d f g f g d 16