Tree Traversals
Table of Contents
Based on Lenhart and Jannen (https://williams-cs.github.io/cs136-f20-www/slides/treeTraversals.pdf)
1 Reading
Read Bailey 12.6.
2 Learning Goals
After this lesson you will be able to
- Describe and implement the four primary tree traverals
3 Slides
You can download the slides that were the basis for the lecture in pdf or PowerPoint.
4 Practice Problems1
- In code that recursively traverses binary trees, how many recursive calls are usually found within the code?
For the following binary tree give the order nodes are visited for a pre-order, an in-order, a post-order traversal, and a level-order traversal.
What does this code do?
public void mystery(BinaryTreeNode<String> node) { if (node == null) { return; } mystery(node.right); mystery(node.left); System.out.println(node.data); }
- Write a method
public void printExpr(BinaryTreeNode<String> expr)
that uses an in-order traversal to print out a correctly parenthesized version of the expression represented by the tree rooted atexpr
.
Footnotes:
1
Solutions:
- Usually 2. Each call handles one subtree.
- When nothing else is said, a left-to-right traversal is assumed.
- Pre-order traversal: GEBDFKMR
- In-order traversal: BDEFGKMR
- Post-order traversal: DBFERMKG
- Level-order traversal: GEKBFMDR
- The code implements a right-to-left post-order traversal (i.e., the right subtree is traversed before the left subtree).
public void printExpr(BinaryTreeNode<String> expr) { if (expr == null) { return; } if (expr.isLeaf()) { System.out.print(expr.data); return; } System.out.print("("); printExpr(expr.left); System.out.print(expr.data); printExpr(expr.right); System.out.print(")"); }