Tree Traversals

# Tree Traversals - Lecture 18 Tree Traversals PIC 10B Todd...

This preview shows pages 1–3. Sign up to view the full content.

1 Lecture 18: Tree Traversals PIC 10B Todd Wittman Tree Traversals s It's unclear how we should print a tree. s Top to bottom? Left to right? s A tree traversal is a specific order in which to trace the nodes of a tree. s There are 3 common tree traversals. 1. in-order : left, root, right 2. pre-order : root, left, right 3. post-order : left, right, root s This order is applied recursively. s So for in-order, we must print each subtree's left branch before we print its root. s Note "pre" and "post" refer to when we visit the root.

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
2 Tree Traversal Example s Let's do an example first. .. 15 5 16 3 12 7 20 18 23 13 10 6 s in-order : (left, root, right) 3, 5, 6, 7, 10, 12, 13, 15, 16, 18, 20, 23 s pre-order : (root, left, right) 15, 5, 3, 12, 10, 6, 7, 13, 16, 20, 18, 23 s post-order : (left, right, root) 3, 7, 6, 10, 13, 12, 5, 18, 23, 20, 16, 15 In-Order Traversal s The in-order traversal is probably the easiest to see, because it sorts the values from smallest to largest. template <typename T> void Tree<T> :: printInOrder (std::ostream& out, TreeNode<T>* rootNode) { if (rootNode != NULL) { printInOrder (out, rootNode->left);
This is the end of the preview. Sign up to access the rest of the document.

### Page1 / 7

Tree Traversals - Lecture 18 Tree Traversals PIC 10B Todd...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online