Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a struct for a binary tree node.
DSA C++
struct Node {
int data;
Node* left;
Node* [1];
Node(int val) : data(val), left(nullptr), right(nullptr) {}
}; Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'parent' instead of 'right' for the right child pointer.
Using 'next' which is common in linked lists but not binary trees.
✗ Incorrect
The right child pointer in a binary tree node is commonly named 'right'.
2fill in blank
mediumComplete the code to insert the root node into the queue for level order traversal.
DSA C++
std::queue<std::pair<Node*, int>> q; q.push([1], 0});
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Pushing root->data instead of root pointer.
Pushing nullptr which causes runtime errors.
✗ Incorrect
We push the root node pointer itself, not its data, into the queue for traversal.
3fill in blank
hardFix the error in the condition to check if a horizontal distance is not yet in the map.
DSA C++
if (topViewMap.find([1]) == topViewMap.end()) { topViewMap[hd] = node->data; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for node->data instead of hd in the map.
Using the map itself as a key.
✗ Incorrect
We check if the horizontal distance 'hd' is in the map, not the node data.
4fill in blank
hardFill both blanks to correctly update the queue with left and right children and their horizontal distances.
DSA C++
if (node->left) q.push({node->left, hd [1] 1}); if (node->right) q.push({node->right, hd [2] 1});
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Adding 1 to left child hd or subtracting 1 from right child hd.
Using multiplication or division instead of addition/subtraction.
✗ Incorrect
Left child horizontal distance is hd - 1; right child is hd + 1.
5fill in blank
hardFill all three blanks to create a map from horizontal distance to node data, and print the top view in order.
DSA C++
std::map<int, int> topViewMap; // After filling topViewMap for (auto [1] : topViewMap) { std::cout << [2] << ' '; } std::cout << std::endl; // Function signature std::vector<int> topView(Node* [3]) { /* ... */ }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Printing the key (first) instead of the value (second).
Using wrong variable names in the loop.
Wrong function parameter name.
✗ Incorrect
We iterate over map pairs, print the second (node data), and the function takes root node pointer.