AV121 DSA KJ Lecture 02 Binary Trees N Ary Trees
AV121 DSA KJ Lecture 02 Binary Trees N Ary Trees
Kurian John
Lecture 02
Lecture 02 – Plan
0 1
0 1
0
1
0
1 0 1 0
0
0
0 1 1 1 1
0
1 1 1 0
1
1
Each node
can have at
most two
child nodes
Postfix expression?
3 4 a × b c + + × d 5 ÷ 6 e – + +
→ Internal nodes store operators
→ Leaf nodes store literals or variables
→ No nodes have just one sub tree
→ The order is not relevant for
• Addition and multiplication (commutative)
→ Order is relevant for
• Subtraction and division (non-commutative)
April-May 2023 AV121 - Data Structures and Algorithms 12
Perfect Binary Trees
A perfect binary tree of height h is a binary tree where
→ All leaf nodes have the same depth h
→ All other nodes are full
Height
0 1 2 3 4 Height
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
parent = k >> 1;
left_child = k << 1;
right_child = left_child | 1;
Problems
0 306 1
→ Tree Building
120 186
1 → Encoding
E
0
1 → Decoding
79 107
0 1 0
65 1
37 42 42 0
U D L
32
0 33 1
C
24
9 M
0 1
2 7
Z K
0 306 1
120 186
1
E
0
107
1
79
0 1 0
65 1
37 42 42 0
U D L
32
0 33 1
C
24
9 M
0 1
2 7
Z K
101
0 306 1
120 186
1
E
0
107
1
79
0 1 0
65 1
37 42 42 0
U D L
32
0 33 1
C
24
9 M
0 1
2 7
Z K
101
0 306 1
120 186
1
E
0
107
1
79
0 1 0
65 1
37 42 42 0
U D L
32
0 33 1
C
24
9 M
0 1
2 7
Z K
101 0
0 306 1
120 186
1
E
0
107
1
79
0 1 0
65 1
37 42 42 0
U D L
32
0 33 1
C
24
9 M
0 1
2 7
Z K
101 0 0 101
0 306 1
120 186
1
E
0
107
1
79
0 1 0
65 1
37 42 42 0
U D L
32
0 33 1
C
24
9 M
0 1
2 7
Z K
0 306 1
120 186
1
E
0
107
1
79
0 1 0
65 1
37 42 42 0
U D L
32
0 33 1
C
24
9 M
0 1
2 7
Z K
0 306 1
120 186
1
E
0
107
1
79
0 1 0
65 1
37 42 42 0
U D L
32
0 33 1
C
24
9 M
0 1
2 7
Z K
M U
0 306 1
120 186
1
E
0
107
1
79
0 1 0
65 1
37 42 42 0
U D L
32
0 33 1
C
24
9 M
0 1
2 7
Z K
M U C
0 306 1
120 186
1
E
0
107
1
79
0 1 0
65 1
37 42 42 0
U D L
32
0 33 1
C
24
9 M
0 1
2 7
Z K
M U C K
0 306 1
120 186
1
E
0
107
1
79
0 1 0
65 1
37 42 42 0
U D L
32
0 33 1
C
24
9 M
0 1
2 7
Z K
h +1
N −1 h
Number of nodes in a perfect N-ary tree of height h, n = N =
k
k =0 N −1
h = log N (n( N − 1) + 1) − 1
A perfect binary tree has approximately log 2 (N) times the height
of an n-ary tree with the same number of nodes
April-May 2023 AV121 - Data Structures and Algorithms 50
N-ary Trees
Trie
→ A trie (derived from
retrieval) is a multiway
tree data structure used
for storing strings over an a d
alphabet. It is used to
store a large number of n a o
strings.
→ Pattern matching can be d t d
done efficiently using
tries
Binary Trees
Definitions
Perfect and Complete Binary Trees, Representation
Applications – Expression / Huffman Trees
N-ary Trees, Tries