Download presentation
Presentation is loading. Please wait.
Published bySuparman Darmali Modified over 6 years ago
1
Extended Introduction to Computer Science CS1001.py
Lecture 21: Constructing Huffman Tree: An example Instructors: Daniel Deutch, Amir Rubinstein Teaching Assistants: Michal Kleinbort, Amir Gilad School of Computer Science Tel-Aviv University 18-Fall Semester, 2017
2
Constructing Huffman Tree
Assume that the character count is [('a', 8), ('b', 3), ('h', 1), ('d', 1), ('e', 1), ('f', 1), ('g', 1), ('c', 1)] The example is adapted from Structure and Interpretation of Computer Programs, by Harold Abelson, Gerald Jay Sussman
3
Priority queue: Initial value
b,3 h,1 d,1 e,1 f,1 g g,1 c,1 The order in the list is not important. We use a naive implementation of priority queue: a list, where we insert elements at the end, and extract minimum is done by finding the minimal element and removing it. More efficient implementation is possible
4
Extract minimum twice:
b,3 h,1 d,1 e,1 f,1 g g,1 c,1
5
Create a new tree: a,8 b,3 e,1 f,1 g g,1 c,1 hd,2 h,1 d,1
6
Insert the new tree into the priority queue:
a,8 b,3 e,1 f,1 g g,1 c,1 h,1 d,1 hd,2
7
Now repeat the process:
b,3 e,1 f,1 g g,1 c,1 h,1 d,1 hd,2
8
a,8 b,3 g g,1 c,1 h,1 d,1 hd,2 ef,2 e,1 f,1
9
a,8 b,3 g g,1 c,1 h,1 d,1 hd,2 e,1 f,1 ef,2
10
a,8 b,3 h,1 d,1 hd,2 e,1 f,1 ef,2 g g,1 c,1 gc,2
11
a,8 b,3 h,1 d,1 hd,2 g g,1 c,1 gc,2 e,1 f,1 ef,2
12
a,8 b,3 g g,1 c,1 gc,2 h,1 d,1 hd,2 e,1 f,1 ef,2 hdef,4
13
a,8 b,3 g g,1 c,1 gc,2 h,1 d,1 hd,2 e,1 f,1 ef,2 hdef,4
14
a,8 h,1 d,1 hd,2 e,1 f,1 ef,2 hdef,4 b,3 g g,1 c,1 gc,2 gcb,5
15
b,3 g g,1 c,1 gc,2 gcb,5 a,8 h,1 d,1 hd,2 e,1 f,1 ef,2 hdef,4
16
a,8 h,1 d,1 hd,2 e,1 f,1 ef,2 hdef,4 b,3 g,1 c,1 gc,2 gcb,5 hdefgcb,9
17
h,1 d,1 hd,2 e,1 f,1 ef,2 hdef,4 b,3 g,1 c,1 gc,2 gcb,5 hdefgcb,9 a,8
18
a,8 h,1 d,1 hd,2 e,1 f,1 ef,2 hdef,4 b,3 g,1 c,1 gc,2 gcb,5 hdefgcb,9
hdefgcba,17
19
The queue contains a single element. Loop ends
hd,2 e,1 f,1 ef,2 hdef,4 b,3 g g,1 c,1 gc,2 gcb,5 hdefgcb,9 hdefgcba,17 The queue contains a single element. Loop ends
20
a h d e f b g c 1 1 1 1 1 1 1 Now we can create the codes for each letter by following the paths from the root to the leaves. Eg a → 0, h → 1000, f → 1011, ….
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.