Gerald Samson
Gerald Samson
Gerald Samson
TREE
ITRODUCTION
2
4 6 7
5
8 9
04 of 15
1. Sets.
2. Multisets.
3. Associative arrays
52
15
56
54 61
9 11
3 5
Binary Trees
•Binary tree: Each node has at most 2 children
(branching factor 2)
•Binary tree is
• A root (with data)
• A left subtree (may be empty)
• A right subtree (may be empty)
Given a sorted array key [0.. n-1] of search keys and an array freq[0.. n-1] of
frequency counts, where freq[i] is the number of searches for keys[i]. Construct a
binary search tree of all keys such that the total cost of all the searches is as small as
possible.
Let us first define the cost of a BST. The cost of a BST node is the level of that node
multiplied by its frequency. The level of the root is 1.
EXAMPLE
Input: keys[] = {10, 12}, freq[] = {34, 50}
There can be following two possible BSTs
10 12
\ /
12 10
I II
Frequency of searches of 10 and 12 are 34 and 50
respectively.
The cost of tree I is 34*1 + 50*2 = 134
The cost of tree II is 50*1 + 34*2 = 118