# Traversals

Télécharger la présentation

## Traversals

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
##### Presentation Transcript

1. Traversals • Common set of algoritms on trees are traversals • A way of visiting all the nodes of a tree • “Visit” is defined as performing one operation on a node a b c g d f e h i

2. Traversals • Three basic traversals • Preorder • Postorder • Inorder

3. Preorder Traversal • A traversal visits the nodes of a tree in a systematic manner • In a preorder traversal, a node is visited before its descendants • Application: print a structured document AlgorithmpreOrder(v) visit(v) foreachchild w of v preorder (w) 1 Make Money Fast! 2 5 9 1. Motivations 2. Methods References 6 7 8 3 4 2.3 BankRobbery 2.1 StockFraud 2.2 PonziScheme 1.1 Greed 1.2 Avidity Demo

4. Postorder Traversal AlgorithmpostOrder(v) foreachchild w of v postOrder (w) visit(v) • In a postorder traversal, a node is visited after its descendants • Application: compute space used by files in a directory and its subdirectories 9 cs16/ 8 3 7 todo.txt1K homeworks/ programs/ 4 5 6 1 2 Robot.java20K h1c.doc3K h1nc.doc2K DDR.java10K Stocks.java25K Demo

5. 6 2 8 1 4 7 9 3 5 Inorder Traversal • In an inorder traversal a node is visited after its left subtree and before its right subtree • More later when we discuss binary trees

6. Traversal Worksheet Postorder Preorder

7. B    A D F   C E Linked Structure for Trees • A node is represented by an object storing • Element • Parent node • Sequence of children nodes • Node objects implement the Position ADT B A D F C E