Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a priority queue for Huffman nodes.
DSA C++
std::priority_queue<Node*, std::vector<Node*>, [1]> pq;Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong comparator class name.
Forgetting to specify the comparator in the priority queue.
✗ Incorrect
The priority queue needs a comparator class named NodeComparator to order nodes by frequency.
2fill in blank
mediumComplete the code to merge two nodes into a new parent node.
DSA C++
Node* parent = new Node([1] + [2], nullptr, left, right);
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong member name like frequency instead of freq.
Adding only one node's frequency.
✗ Incorrect
The parent node frequency is the sum of left and right node frequencies, accessed by left->freq and right->freq.
3fill in blank
hardFix the error in the recursive function to assign codes to characters.
DSA C++
void assignCodes(Node* root, std::string code) {
if (!root) return;
if (!root->left && !root->right) {
codes[root->ch] = [1];
}
assignCodes(root->left, code + "0");
assignCodes(root->right, code + "1");
}Attempts:
3 left
💡 Hint
Common Mistakes
Assigning root->code which does not exist.
Assigning frequency instead of code string.
✗ Incorrect
The code string built during recursion should be assigned to the character's code in the map.
4fill in blank
hardFill both blanks to build the Huffman tree by combining nodes.
DSA C++
while (pq.size() > 1) { Node* left = pq.top(); pq.pop(); Node* right = pq.top(); pq.pop(); Node* parent = new Node([1] + [2], nullptr, left, right); pq.push(parent); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect member names like frequency.
Adding only one node's frequency.
✗ Incorrect
The parent node frequency is the sum of left and right node frequencies accessed by left->freq and right->freq.
5fill in blank
hardFill all three blanks to create a map of character codes using recursion.
DSA C++
void assignCodes(Node* root, std::string [1]) { if (!root) return; if (!root->left && !root->right) { codes[[2]] = [3]; } assignCodes(root->left, code + "0"); assignCodes(root->right, code + "1"); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong parameter names.
Assigning frequency instead of code string.
✗ Incorrect
The function parameter is named code, the character is root->ch, and the code string assigned is code.
