Other/Huffman Coding.cpp
// Building the Huffman Tree using the heap method
// O(NlogN)
Building the Huffman Tree using the heap method
O(NlogN)
Building the Huffman Tree using the heap method O ( NlogN )
void build_heap()
{
    priority_queue<TreeNode*, vector<TreeNode*>, cmp> pq;
    for(auto &x : freq)
    {
        loc[x.first] = new TreeNode(x.first, x.second);
        pq.push(loc[x.first]);
    }
    while(pq.size() > 1)
    {
        TreeNode* a = pq.top();
        pq.pop();
        TreeNode* b = pq.top();
        pq.pop();
        TreeNode* nw = new TreeNode(a, b);
        a -> parent = b -> parent = nw;
        pq.push(nw);
    }
    root = pq.top();
    return;
}
void build_heap ( ) { priority_queue < TreeNode * , vector < TreeNode * > , cmp > pq ; for ( auto & x : freq ) { loc [ x . first ] = new TreeNode ( x . first , x . second ) ; pq . push ( loc [ x . first ] ) ; } while ( pq . size ( ) > 1 ) { TreeNode * a = pq . top ( ) ; pq . pop ( ) ; TreeNode * b = pq . top ( ) ; pq . pop ( ) ; TreeNode * nw = new TreeNode ( a , b ) ; a -> parent = b -> parent = nw ; pq . push ( nw ) ; } root = pq . top ( ) ; return ; }
Building the Huffman Tree using the heap method
O(NlogN)
Building the Huffman Tree using the heap method O ( NlogN )
// create all the leaves // a and b are the least probable, so we merge them // set the root