Download Expression Trees and Huffman Encoding and more Slides Data Structures and Algorithms in PDF only on Docsity!
1
Expression Tree
The inner nodes contain operators while leaf
nodes contain operands.
a
c
b
g
d
e
f
2
Expression Tree
The tree is binary because the operators are
binary.
a
c
b
g
d
e
f
4
Expression Tree
Inorder traversal yields: a+bc+de+f*g
a
c
b
g
d
e
f
5
Enforcing Parenthesis
void inorder(TreeNode* treeNode)
if( treeNode != NULL ){
cout << "(";
inorder(treeNode->getLeft());
cout << ")";
cout << *(treeNode->getInfo());
cout << "(";
inorder(treeNode->getRight());
cout << ")";
7
Expression Tree
Postorder traversal: a b c * + d e * f + g * +
which is the postfix form.
a
c
b
g
d
e
f
8
Constructing Expression Tree
Algorithm to convert postfix expression into an
expression tree.
We already have an expression to convert an
infix expression to postfix.
Read a symbol from the postfix expression.
If symbol is an operand, put it in a one node tree
and push it on a stack.
If symbol is an operator, pop two trees from the
stack, form a new tree with operator as the root
and T 1 and T 2 as left and right subtrees and
push this tree on the stack.
10
Constructing Expression Tree
a b + c d e + * *
a b
Stack is growing left to right
If symbol is an operand, put it in a one node tree and push it on a stack.
top
11
Constructing Expression Tree
a b + c d e + * *
a b
Stack is growing left to right
If symbol is an operator, pop two trees from the stack, form a new tree with operator as the root and T 1 and T 2 as left and right subtrees and push this tree on the stack.
13
Constructing Expression Tree
a b + c d e + * *
a b
d e
14
Constructing Expression Tree
a b + c d e + * *
a b
c
d e
16
Other Uses of Binary Trees
Huffman Encoding
17
Huffman Encoding
Data compression plays a significant role in
computer networks.
To transmit data to its destination faster, it is
necessary to either increase the data rate of the
transmission media or to simply send less data.
Improvements with regard to the transmission
media has led to increase in the rate.
The other options is to send less data by means
of data compression.
Compression methods are used for text, images,
voice and other types of data (space probes).
19
Huffman Encoding
To understand Huffman encoding, it is
best to use a simple example.
Encoding the 32-character phrase:
" traversing threaded binary trees ",
If we send the phrase as a message in a
network using standard 8-bit ASCII codes,
we would have to send 8*32= 256 bits.
Using the Huffman algorithm, we can send
the message with only 116 bits.
20
Huffman Encoding
List all the letters used, including the "space"
character, along with the frequency with which
they occur in the message.
Consider each of these (character,frequency)
pairs to be nodes; they are actually leaf nodes,
as we will see.
Pick the two nodes with the lowest frequency,
and if there is a tie, pick randomly amongst
those with equal frequencies.