Data Structures and Algorithms
Serializing Trees, General Trees Chris Brooks Department of Computer Science University of San Francisco
Department o...
Serializing Trees, General Trees Chris Brooks Department of Computer Science University of San Francisco
Department of Computer Science — University of San Francisco – p.1/20
11-0:
Dealing with Project 2
Basic steps to compress: Read in a text file Count the frequency of each character Build Huffman tree Build lookup table from tree Write tree out to file Write compressed characters out to file.
Department of Computer Science — University of San Francisco – p.2/20
11-1:
Dealing with Project 2
Basic steps to uncompress: Open binary file Read in and rebuild tree Use tree to decode remaining characters
Department of Computer Science — University of San Francisco – p.3/20
11-2:
Reading from files
You can use the provided TextFile and BinaryFile classes for this. Start by writing a program that opens a text file or binary file, reads each character/byte, and writes to standard out. Step 2: Add in frequency counting.
Department of Computer Science — University of San Francisco – p.4/20
11-3:
Dealing with the Huffman tree
Step 3: Build a huffman tree Build one tree for each character Combine two lowest-frequency characters. See last week’s notes. Once tree is finished, do a preorder traversal to get a lookup table.
Department of Computer Science — University of San Francisco – p.5/20
11-4:
Serializing Binary Trees
Print a tree to a file, saving structure information First Try: Print out nodes, in order that they would appear in a PREORDER traversal. Why doesn’t this work?
A B D
C E
F
G ABDEGCF
Department of Computer Science — University of San Francisco – p.6/20
11-5:
Serializing Binary Trees
Printing out nodes, in order that they would appear in a PREORDER traversal does not work, because we don’t know when we’ve hit a null pointer Store null pointers, too!
A B D
C E
F
G ABD//EG///C/F//
Department of Computer Science — University of San Francisco – p.7/20
11-6:
Serializing Binary Trees
In most trees, more null pointers than internal nodes Instead of marking null pointers, mark internal nodes Still need to mark some nulls, for nodes with 1 child
A B D
C E
F
G A’B’DE’G/C’/F
Department of Computer Science — University of San Francisco – p.8/20
11-7:
Trees with > 2 children
We might want to have a tree with more than two children How can we implement this?
Department of Computer Science — University of San Francisco – p.9/20
11-8:
Trees with > 2 children
Array of Children
Department of Computer Science — University of San Francisco – p.10/20
11-9:
Trees with > 2 children
Linked List of Children
Department of Computer Science — University of San Francisco – p.11/20
11-10:
Left Child / Right Sibling
We can integrate the linked lists with the nodes themselves:
Department of Computer Science — University of San Francisco – p.12/20