MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Binary Tree Traversals: DFS (Pre, In, Post) & BFS Level-Order0%
Study Materials
Data Structures & AlgorithmsProgress 0%
1.1Introduction to DSA, Big-O, Big-Omega & Big-Theta Notations1.2Time Complexity Calculation Rules & Common Runtime Patterns1.3Space Complexity, Auxiliary Memory & Stack vs Heap Allocation
7.1Binary Tree Traversals: DFS (Pre, In, Post) & BFS Level-Order7.2Binary Search Trees (BST): Insertion, Deletion, Validation & Inorder Sorting7.3Heaps & Priority Queues: Min-Heap, Max-Heap, Heapify & Top-K Elements
HomeTutorialsData Structures & AlgorithmsBinary Tree Traversals: DFS (Pre, In, Post) & BFS Level-Order
Binary Search Trees (BST): Insertion, Deletion, Validation & Inorder Sorting

Binary Tree Traversals: DFS (Pre, In, Post) & BFS Level-Order

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

A Binary Tree is a non-linear hierarchical data structure in which each node has at most two children, referred to as the left child and the right child. Binary trees are the building blocks of Binary Search Trees (BST), Heaps, Expression Parsers, and Huffman Coding.


1. Real-World Analogy: Family Genealogy & File Directories

Think of a computer file system directory tree:

  • Root folder (/) contains subfolders (/home, /etc).
  • Each subfolder contains child files and directories.
  • To scan every file on your computer, you can either:
  1. 1
    Explore deeply down one folder branch until the bottom before backtracking (Depth-First Search - DFS).
  2. 2
    Inspect all immediate files in the current folder, then all files 1 level down, then 2 levels down (Breadth-First Search - BFS).

2. Binary Tree Architectural Diagram

Binary Tree and Heap StructureClick to Zoom
Binary Tree and Heap Structure

3. The 4 Essential Tree Traversals

Depth-First Search (DFS) Variants:

  1. 1
    Preorder (Root → Left → Right): Useful for cloning/serializing trees.
  2. 2
    Inorder (Left → Root → Right): In a BST, produces sorted numerical order!
  3. 3
    Postorder (Left → Right → Root): Bottom-up evaluation (deleting trees, calculating folder sizes).

Breadth-First Search (BFS):

  1. 1
    Level-Order: Traverses tree level-by-level from top to bottom using a FIFO Queue.
1 1
2 / \
3 2 3
4 / \
5 4 5
6 
7Preorder: 1 -> 2 -> 4 -> 5 -> 3
8Inorder: 4 -> 2 -> 5 -> 1 -> 3
9Postorder: 4 -> 5 -> 2 -> 3 -> 1
10Level-Order:1 -> 2 -> 3 -> 4 -> 5

4. Multi-Language Implementations

Python 3:

1from collections import deque
2 
3class TreeNode:
4 def __init__(self, val: int = 0, left=None, right=None):
5 self.val = val
6 self.left = left
7 self.right = right
8 
9# 1. Inorder Traversal (DFS)
10def inorder_traversal(root: TreeNode) -> list[int]:
11 result = []
12 def dfs(node):
13 if not node:
14 return
15 dfs(node.left) # 1. Traverse Left
16 result.append(node.val) # 2. Visit Root
17 dfs(node.right) # 3. Traverse Right
18 dfs(root)
19 return result
20 
21# 2. Level-Order Traversal (BFS)
22def level_order(root: TreeNode) -> list[list[int]]:
23 if not root:
24 return []
25 levels = []
26 queue = deque([root])
27
28 while queue:
29 level_size = len(queue)
30 current_level = []
31 for _ in range(level_size):
32 node = queue.popleft()
33 current_level.append(node.val)
34 if node.left:
35 queue.append(node.left)
36 if node.right:
37 queue.append(node.right)
38 levels.append(current_level)
39
40 return levels

Modern JavaScript / TypeScript:

1export class TreeNode {
2 val: number;
3 left: TreeNode | null = null;
4 right: TreeNode | null = null;
5 constructor(val: number) {
6 this.val = val;
7 }
8}
9 
10// Inorder Traversal
11export function inorderTraversal(root: TreeNode | null): number[] {
12 const result: number[] = [];
13 function dfs(node: TreeNode | null): void {
14 if (!node) return;
15 dfs(node.left);
16 result.push(node.val);
17 dfs(node.right);
18 }
19 dfs(root);
20 return result;
21}
22 
23// Level-Order Traversal (BFS)
24export function levelOrder(root: TreeNode | null): number[][] {
25 if (!root) return [];
26 const levels: number[][] = [];
27 const queue: TreeNode[] = [root];
28 
29 while (queue.length > 0) {
30 const levelSize = queue.length;
31 const currentLevel: number[] = [];
32 
33 for (let i = 0; i < levelSize; i++) {
34 const node = queue.shift()!;
35 currentLevel.push(node.val);
36 if (node.left) queue.push(node.left);
37 if (node.right) queue.push(node.right);
38 }
39 
40 levels.push(currentLevel);
41 }
42 
43 return levels;
44}

5. Trace Table: Level-Order BFS on Example Tree

IterationActive Queue at StartlevelSizeDequeued Nodes & Added to LevelQueue After Adding Children
Level 0[1]1Dequeue 1 → Level: [1][2, 3]
Level 1[2, 3]2Dequeue 2 (add 4,5), Dequeue 3[4, 5]
Level 2[4, 5]2Dequeue 4, Dequeue 5[] (Empty → Done!)

Interactive Quiz• Knowledge Check

Multiple Choice Questions

Question 1
In which order does an "Inorder Traversal" visit the components of a subtree?
Question 2
What data structure is fundamentally required to implement Level-Order (BFS) tree traversal?
Question 3
What is the maximum number of nodes at level $L$ of a binary tree (where root is level 0)?
Question 4
In a Binary Search Tree (BST), which traversal produces the node values in strictly ascending sorted order?
Question 5
What is the time complexity of traversing all $n$ nodes of a binary tree using DFS or BFS?

Next Lesson

Binary Search Trees (BST): Insertion, Deletion, Validation & Inorder Sorting

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Quick Sort: Lomuto vs Hoare Partitioning & Pivot StrategiesBinary Search Trees (BST): Insertion, Deletion, Validation & Inorder Sorting

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Data Structures & Algorithms with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext