BS Artificial Intelligence · Semester 1 · Week 15

Discrete Mathematics for BSAI

Rooted Trees and Traversals

Dr. Hira Benish
Associate Professor & HoD, Mathematics
PMAI Lab, Mathematics Behind AI

Week 15 · Dr. Hira BenishBegin reading  

01 · Opening Scenario: Follow a Decision or Explore Them All?

A student-support guide asks whether a learner needs help now. If yes, it asks one follow-up question and suggests support. If no, it asks a different question and offers a learning resource. A learner follows one branch at a time. But how could an editor systematically visit every question and outcome in the guide?

Predict: Following a learner's answers may reach only one final action. Checking the whole guide requires visiting all branches. A rooted tree represents the branches; a traversal specifies the order in which we visit every node.

Central question

Are we following one route to a decision, or visiting the entire tree in a specified order?

02 · Learning Objectives and Three-Hour Guide

By the end of Week 15, you should be able to identify a root, parent, child, leaf and depth; draw a small rooted binary tree from stated decisions; trace preorder, inorder, postorder and level order; distinguish one decision path from a complete traversal; and explain what different visit orders accomplish.

Class timeEssential work
45 minBuild a paper tree; root, children, leaves and depth
75 minHand traces and student-as-node traversal practice
45 minSmaller Case Study 5: one decision path versus whole-tree visits
15 minTraversal Explorer and exit check

Classroom essentials Sections 01–12 and Practice 1–6. Optional self-study Colab and Practice 7. The visual step-through is a check after a paper trace.

03 · A Root Gives Direction to the Branches

A tree is a connected graph with no cycle. Choose one vertex as the root; it is the starting point for describing downward branches. In the diagram below A is the root. B and C are its children, while A is their parent. D and E are children of B; F and G are children of C.

Root A branches left to B and right to C; B branches to D and E; C branches to F and G ABCDEFG depth 0depth 1depth 2
Figure 1. The root has depth 0. B and C have depth 1; leaves D, E, F and G have depth 2.

A leaf has no children: D, E, F and G are leaves. Depth is the number of edges from the root to a node. For example, A→B→E uses two edges, so E has depth 2. The subtree at B consists of B and its descendants D and E.

Quick check: The root is at depth 0, not depth 1. There is no edge from A to itself.

04 · Left and Right Matter in a Binary Tree

A binary tree has at most two children at each node, identified as left and right. In Figure 1, B is the left child of A and C the right child. D is left of B, E right of B; F is left of C, G right of C.

The left/right positions are part of this tree's information. If we swap B and C together with their subtrees, the shapes may look similar, but the left-before-right traversal results change. A childless leaf has neither a left nor a right child.

NodeLeft childRight childDepth
ABC0
BDE1
CFG1
D, E, F, GNoneNone2

05 · Following Answers Visits One Path

Suppose A asks “Needs support now?” A yes answer moves left to B, which asks “Missed several checkpoints?” A no answer at B moves right to E, the study-session suggestion. The decision path is A → B → E. We did not visit C, D, F or G.

A decision tree models a specified series of questions and outcomes. It does not automatically learn from data, establish that a recommendation works, or know unstated facts. Its branch labels and rules must be supplied and checked by people.

Quick interpretation: Following one path gives one recommendation under the supplied answers. Visiting all seven nodes is a separate task, such as reviewing every branch of the guide.

06 · A Traversal Visits Every Node

A traversal is an ordered visit of the entire tree. We will use four orders on the same seven-node tree. The letters in a visit list describe when each node is recorded; moving through the drawing to reach another node does not add an extra recorded visit.

OrderSmall instructionWhere the root A appears
PreorderRecord node, then left subtree, then right subtreeFirst
Inorder (binary tree)Left subtree, then record node, then right subtreeBetween left and right
PostorderLeft subtree, then right subtree, then record nodeLast
Level orderDepth 0, then depth 1, then depth 2; left to right on each levelFirst

For the first three orders, apply the same instruction within each smaller subtree. Level order proceeds across a whole depth before moving down.

07 · Preorder: Node Before Its Children

Begin at A and record it. Then finish the left subtree rooted at B: record B, D, E. Finally finish the right subtree rooted at C: record C, F, G.

Preorder: A, B, D, E, C, F, G.

Worked trace

At B, the same rule applies: record B before its left child D and right child E. Do not record A again when you return from the B subtree. The recorded list contains each of the seven nodes exactly once.

Preorder is useful when we want to see each parent before its descendants, such as presenting the outline of a branching guide from the top.

08 · Inorder: Root Between Left and Right

Inorder is defined here for a binary tree with identified left and right children. First traverse A's left subtree: D, B, E. Record A. Then traverse A's right subtree: F, C, G.

Inorder: D, B, E, A, F, C, G.

At B, the instruction “left, node, right” becomes D, B, E. At C it becomes F, C, G. A leaf is recorded when reached because it has no child subtrees to visit first.

Common misconception: Inorder is not automatically alphabetical or sorted. This tree is a decision guide, not a binary search tree with an ordering rule.

09 · Postorder: Children Before Parent

Finish B's children D and E before recording B; finish C's children F and G before recording C; then record the root A.

Postorder: D, E, B, F, G, C, A.

This order makes the parent appear after both of its subtrees. For example, when reviewing a guide from its outcomes back to its earlier questions, one could inspect the leaf outcomes before recording their parent question. The traversal order alone does not determine whether the guide is correct.

10 · Level Order: Across Each Depth

Record A at depth 0. Then B and C at depth 1, left to right. Then D, E, F and G at depth 2, left to right.

Level order: A, B, C, D, E, F, G.

Level order differs from preorder: after B, level order visits C before going down to D. This is useful when we want to inspect all questions at one depth before inspecting deeper outcomes.

Quick check: Which nodes are at depth 2? D, E, F and G. Their left-to-right sequence is the last four entries of level order.

11 · Traversal Explorer

Predict → Test → Explain First write the full visit list on paper. Choose an order, predict the next recorded node, and check it. The diagram highlights nodes as they are recorded. A wrong guess leaves the step available for another try.

Build the visit order

Record node, left subtree, right subtree.

Interactive binary tree with root A, children B C, and leaves D E F G ABCDEFG

Predict the first recorded node.

Recorded: — · Step 0 of 7

12 · Smaller Case Study 5: Exploring a Decision Tree

Scenario → Understand → Represent → Reason → Test → Interpret. A student-support guide has three yes/no questions and four possible actions. The seven nodes are the same ones in Figure 1, now with specific meanings:

NodeQuestion or actionLeft / yesRight / no
ANeeds support now?BC
BMissed several checkpoints?DE
CWants practice?FG
DAdvisor meeting——
EStudy session——
FPractice set——
GResource list——

Follow one learner

The learner answers yes at A and no at B. The path is A → B → E, leading to a study-session suggestion. No statement about C or its children is used for this learner. If the learner instead answers no at A and yes at C, the path is A → C → F.

Explore the whole guide

An editor may need to inspect every node. Preorder records a parent question before its branches: A,B,D,E,C,F,G. Level order examines the top question, then both second-level questions, then all four actions: A,B,C,D,E,F,G. Both visit all seven nodes; they differ in when C is inspected.

Interpret the model

The tree describes only the questions, answers and actions supplied here. It does not infer a student's needs from data or learn better rules. The action is a transparent recommendation under stated answers, not a diagnosis or proof of effectiveness.

Case reflection

Draw the tree from the table, mark the path A→B→E, and write a preorder and level-order list. In two sentences, explain why the path and traversals answer different questions.

13 · Optional Colab: Check One Hand Trace

Self-study · mathematics first Finish the paper preorder trace before running code. The small nested representation below stores each node as (label, left child, right child). None means that a child is absent. Parentheses group those three pieces; the whole structure follows the drawing.

tree = (
    "A",
    ("B", ("D", None, None), ("E", None, None)),
    ("C", ("F", None, None), ("G", None, None))
)

The next function reuses the recursive idea from Week 10. It stops at None. Otherwise, it separates one node into its label, left child and right child, prints the label first, and then visits the two children in that order.

def preorder(node):
    if node is None:
        return
    label, left, right = node
    print(label)
    preorder(left)
    preorder(right)

preorder(tree)

Predict A, B, D, E, C, F, G on separate lines. return at an absent child is the stopping case. This small check prints the preorder only; the other three orders remain hand-trace exercises first.

14 · Practice and Exit Check

Draw or point to the stated tree before writing each order. Selected solutions are at the end.

  1. For Figure 1, give the root, B's parent and children, the leaves, and the depths of A, C and E.
  2. Write preorder, inorder, postorder and level order of the Figure 1 tree. Underline the root in each list.
  3. In the case study, a learner answers no at A and yes at C. Give the path and outcome. Is that path a traversal of the whole tree?
  4. A different binary tree has root P; left child Q and right child R; Q has only a left child S; R has left child T and right child U. Draw it and find all four traversal orders.
  5. Explain why inorder requires identified left and right children. If B and C swap positions with their subtrees in Figure 1, which preorder comes next?
  6. An editor wishes to inspect all depth-1 questions before any leaf actions. Which traversal suits that aim? Show its list on Figure 1.
  7. A learner says “Inorder is always alphabetical, because it lists D before B.” Identify the missing assumption and give the actual inorder list for Figure 1.
Exit check: State one difference between a decision path and a full traversal. For the Figure 1 tree, write the first three nodes of preorder and level order, and explain why the third entries differ.

15 · Common Mistakes

Tempting moveRepair
Count the root at depth 1.Depth counts edges from root; A is at depth 0.
Call A→B→E a complete traversal.It follows one answer path and omits other nodes.
Record A again when returning from the B subtree.A traversal list records each node exactly once.
Put A first in postorder.Postorder records left and right subtrees before the parent.
Use inorder without defined left and right child positions.Inorder here applies to a binary tree with left/right roles.
Assume an inorder list must be sorted.Sorted inorder requires an additional search-tree ordering rule, absent here.

16 · Summary

  • A rooted tree has a chosen starting vertex. Parent/child relations follow outward from it; leaves have no children, and depth counts edges from root.
  • A binary tree distinguishes left and right children. Preorder is node-left-right; inorder is left-node-right; postorder is left-right-node.
  • Level order visits all nodes at each depth from left to right before going deeper.
  • One learner's answer path reaches one action; a traversal records every node once.
  • The case-study guide applies stated questions and branches. Its structure does not learn from data.

17 · Visual Concept Map

A rooted binary tree supports a single decision path or four whole-tree traversal orders: preorder, inorder, postorder and level order ROOTED BINARY TREEONE DECISION PATHWHOLE-TREE TRAVERSALDEPTH FIRSTLEVEL ORDER left and right childrenFollow stated answersRecord every node oncepre / in / postacross each depth
Decide whether the task asks for one answer path or an order for visiting every node.

18 · Looking Ahead

Week 16 is integrated revision and final-examination preparation. We will compare models and reasoning methods already taught—logic, proofs, sets, sequences, counting, graph routes and tree traversals—without introducing new mathematical material.

Selected Solutions

Traversal Explorer

Preorder: A,B,D,E,C,F,G. Inorder: D,B,E,A,F,C,G. Postorder: D,E,B,F,G,C,A. Level order: A,B,C,D,E,F,G. A appears first in preorder and level order, between the two subtrees in inorder, and last in postorder.

1 · Structure

Root A. B's parent is A; children are D and E. Leaves are D,E,F,G. Depths: A=0, C=1, E=2.

2 · Four orders

They are listed under Traversal Explorer above. Every list contains each of A–G exactly once.

3 · One path

No at A goes to C; yes at C goes to F, a practice set. Path A→C→F is not a complete traversal; it omits B,D,E,G.

4 · Asymmetric binary tree

With S left of Q and T,U left/right of R: preorder P,Q,S,R,T,U; inorder S,Q,P,T,R,U; postorder S,Q,T,U,R,P; level order P,Q,R,S,T,U.

5 · Swap subtrees

Inorder needs a defined left subtree and right subtree to specify the visits around a parent. After swapping B and C subtrees, preorder is A,C,F,G,B,D,E.

6–7 · Visit depth and ordering

Level order fits the editor's goal: A,B,C,D,E,F,G. Inorder is D,B,E,A,F,C,G. It is not alphabetical; no search-tree ordering rule was supplied.

Exit check

A path follows the answers to one action; a traversal records every node. Preorder begins A,B,D; level order begins A,B,C. Preorder descends into B's subtree, while level order finishes depth 1 first.