UPI Study › Courses › Discrete Mathematics › Free lessons › Lesson 11.2 Free with a free account
Tree Traversal Methods
Discrete Mathematics · Chapter 11: Trees, Spanning Trees, and Minimum Cost NetworksSection 11.2 · lesson 72 of 879 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Discrete Mathematics.
Lesson complete
Earn the 4 college credits for Discrete Mathematics
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Sorting with Trees: Benefits and Limitations →← Trees: Properties and DefinitionsNext lesson: Sorting with Trees: Benefits and Limitations →
In this lesson
4 systematic ways to visit every node exactly once.
- Trace pre-order, in-order and post-order
- Explain why in-order needs a binary tree
- Compute a level-order traversal with a queue
- Match each order to the job it does best
Transcript
Everything said in the video, section by section (1,309 words). Read along, or search it.
Trees, Spanning Trees, and Minimum Cost Networks
Tree Traversal Methods
Once data lives in a tree, almost every task starts by visiting its nodes in some order. This section develops four traversal orders: pre-order, in-order, post-order and level-order. Each visits every node exactly once, and each is useful for a different job.
The Opening Problem
One Expression, 3 Jobs
Every calculator app, spreadsheet formula engine and compiler has to make sense of an expression like two plus five, times nine minus six. Internally, these systems almost never work with the flat string of characters. They parse it into a tree, with each operator as a node, and its operands as children. Once the expression is a tree, very different jobs, like printing it back out, evaluating it to a number, or saving it for another program, all come down to one question. In what order should the nodes be visited? Visiting every node exactly once, by a systematic rule, is called a tree traversal.
11.2.1
3 Depth-First Orders
Traversals are defined recursively. In a binary tree, every node has at most two children, a left child and a right child. Take a tree rooted at v, with a left subtree and a right subtree. Either may be empty, and an empty subtree just contributes nothing. Pre-order visits v first, then traverses the left subtree, then the right. In-order traverses the left subtree, then visits v, then traverses the right. Post-order traverses the left subtree, then the right, and visits v last. The only difference is when the root is visited. All three are depth-first. Each recursive call follows one subtree all the way down before backtracking to the other.
Worked Example
Pre-order on (2 + 5) × (9 − 6)
Here's the expression tree. The root is the outermost operator, times. Its left child is the subtree for two plus five, and its right child is the subtree for nine minus six. Pre-order visits each node before either of its subtrees. So record times. Then go left into the plus subtree: record plus, then two, then five. Then go right into the minus subtree: record minus, then nine, then six. The pre-order sequence is times, plus, two, five, minus, nine, six. Read left to right, that's prefix notation, also called Polish notation. Each operator appears immediately before its two operands.
Worked Example
In-order and Post-order
In-order visits the left subtree, then the root, then the right subtree, at every level. The left subtree gives two, plus, five. Then comes the root, times. Then the right subtree gives nine, minus, six. That's exactly the original infix sequence of tokens. But it's only the tokens, not the parentheses. On its own, it can't distinguish the original expression from two plus five times nine minus six, with no grouping. Post-order visits both subtrees before the root. That gives two, five, plus, then nine, six, minus, and finally times. That's postfix notation, or Reverse Polish, and it's unambiguous with no parentheses at all. Read left to right, pushing operands onto a stack. Each operator combines the two most recent values. Push two and five, and plus gives seven. Push nine and six, and minus gives three. Then times combines seven and three, giving twenty-one. That matches the original expression.
Listing 1
3 Functions, One Line Moved
In Python, the three functions are nearly identical. Each returns immediately on an empty subtree. Otherwise, it records the node's value, and recurses on the left and right children. The only difference is where the recording line sits. First for pre-order, between the two calls for in-order, and last for post-order. Run on the expression tree, using a letter x for times, they return exactly the three sequences we traced.
11.2.2
Why In-order Needs Left and Right
These definitions lean on the binary structure more than they first appear to. Pre-order and post-order generalize easily to a general, or k-ary, tree, where a node may have any number of children. Visit the root, then recurse on each child from left to right. Or recurse on each child first, then visit the root. Take a project folder, Project, holding three subfolders, Docs, Src and Tests. Docs holds one file, Guide. General pre-order gives Project, Docs, Guide, Src, Tests. General post-order gives Guide, Docs, Src, Tests, and finally Project. In-order doesn't survive. Its rule says visit the root between the left and right subtrees. With three children, there's no canonical place for the root. After the first child, or after the second? Either choice is arbitrary.
Listing 2
Pre-order on a General Tree
For a general tree, each node keeps a list of children instead of fixed left and right references. Pre-order records the node, then loops over its children from left to right, recursing on each. On the project tree, it returns Project, Docs, Guide, Src, Tests. And the same loop would work unchanged, whether Project had two children or twenty.
11.2.3
Level-order: Breadth-First
The three orders so far all go deep before going wide. Level-order does the opposite. It visits every node at depth zero, then every node at depth one, then depth two, and so on, left to right within each level. That's a breadth-first strategy. It's computed with a first-in, first-out queue. Put the root in the queue. Then repeatedly remove the front node, visit it, and add its children to the back, until the queue is empty. On the expression tree, the queue starts with times. Remove times, and add plus and minus. Remove plus, and add two and five. Remove minus, and add nine and six. The last four are leaves, so they're just removed and visited in order. The level-order sequence is times, plus, minus, two, five, nine, six.
Listing 3
Level-order With a Queue
Here's level-order in Python, using a double-ended queue. Each step removes a node from the front, skips it if it's empty, records it, and adds its two children to the back. On the expression tree, it returns times, plus, minus, two, five, nine, six. Unlike the depth-first orders, it's naturally iterative. It's the right choice whenever a task processes a tree layer by layer. For example, rendering a user interface one nesting level at a time, or counting the nodes within some number of steps of the root.
Table 1
4 Orders, One Tree
Here are all four sequences on the same tree. The tree never changes. Only the visiting order does. And all four run in theta of n time on a tree with n nodes. For the depth-first orders, each node is handled in exactly one call, which does a constant amount of work of its own. For level-order, each node is added to the queue once and removed once. So they differ in the order of visiting, not in cost.
Table 2
Which Order for Which Job
So which order fits which job? Pre-order writes each parent before its children, so it's the natural way to serialize or copy a tree for easy reconstruction. In-order recovers the infix tokens of an expression. It's the one order that works only for binary trees. Post-order handles bottom-up work, like evaluating an expression, or any total that needs the children's results before the parent's. And level-order processes a tree one depth level at a time. For the calculator, post-order evaluates the expression to twenty-one, pre-order saves it in prefix form, and in-order redisplays something like the original. In-order's best-known use, sorting with a binary search tree, comes in section eleven point three.
Takeaways
Same Tree, Different Order
To summarize. A tree traversal visits every node exactly once, by a systematic rule. Pre-order, in-order and post-order are depth-first, and differ only in where visiting the root falls. In-order is binary-tree-specific, because its rule assumes exactly two subtrees. Pre-order, post-order and level-order all generalize. Level-order is breadth-first, driven by a first-in, first-out queue. And all four run in linear time. Here's something to think about. Take a root A with exactly one child, B. Whether B is a left child or a right child, pre-order gives A, B, and post-order gives B, A. Only in-order tells the two trees apart. In fact, with distinct labels, in-order together with pre-order or post-order always pins down a binary tree. What is it about in-order's rule that resolves left versus right, when the other two miss it?
About Discrete Mathematics at UPI Study
Discrete Mathematics (Math 230) is a self-paced online course of 87 video lessons in 13 chapters, from logic and proof to counting, probability, graph theory and trees. It carries a NCCRS credit recommendation for 4 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus Every course with PRO →
Why take it here
Why students take Discrete Mathematics with UPI Study
Where the credit goes
Universities that work with NCCRS
Discrete Mathematics carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About Tree Traversal Methods
What is the difference between pre-order, in-order, and post-order traversal?
Why does in-order traversal only work on binary trees?
How do you do a level-order traversal with a queue?
Which traversal order should I use to evaluate an expression tree?
About the Discrete Mathematics course
How many college credits is Discrete Mathematics?
How much does Discrete Mathematics cost and what is included?
Which universities accept UPI Study credits?
How long does Discrete Mathematics take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 4 credits in Discrete Mathematics.
87 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
4 credits · NCCRSEnroll →