Q. Where have you seen trees?
ln
command helps you link.) Then, it’s called a directed acyclic graph.
a + b * c - d % e + f
to postfix to evaluation. (Using stacks.) However, now I don’t want that. I want to go to the tree. Prof explained. I couldn’t keep up with the diagrams using Paint. :(
3 ordered traversals
Left:
inorder(T){
inorder(left(T))
val(T)
inorder(right(T))
}
The above traversal of this example will give the output: 11, 32, 33, 35, 42, 50, 60
In general, a left traversal will give in ascending order.
Another one:
preorder(T){
val(T)
preorder(left(T))
preorder(right(T))
}
Scheduling requirements:
findmax()
→ find highest priority element and delete itinsert()
→ add a new element to the collectionLet us look at a traditional implementation before creating a new DS.
(i) Unordered collection of \(n\) elements.
Suppose originally we have array as: |25|31|62|5|2|…|
After findmax()
→ |25|31|5|2|…|
This will have to be \(O(n)\).
insert()
→ can cheaply add the end since we don’t care about order
(ii) Order collection.
findmax()
→ \(O(1)\)
insert()
→ \(O(n)\): note that bin search could give you the location in \(\log n\) but you might need to shift a lot of elements → takes time
If we do \(n\) such operations, we get \(O(n^2)\) in total.
Now, people wanted to create a data structure which does the above two operations well. We call it a priority queue.
(Note that it isn’t a queue. The FIFO isn’t there.)
Q. How do we implement this?
Example: 20, 5, 62, 55, 1, 19, 5, 12
Complete binary tree: A binary tree which is is completely filled, i.e., at level \(l\), we have \(2^l\) nodes.
Thus, total number of nodes will be \(2^{\text{something}} - 1\). In particular, these will be odd. (Unless empty tree.)
Heap
→ fill up levels from top to bottom
→ last level: left to right
Maxheap property → every node is greater than everything in its sub-tree. Pic
It is easy to find max and delete it.
But then we have to patch up the children. For this, we have to traverse till the bottom-most node in worst case. → \(\log n\) by construction.