0
0
DSA C++programming~10 mins

Top View of Binary Tree in DSA C++ - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
Achild
Bparent
Cnext
Dright
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.
2fill in blank
medium

Complete 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'
Aroot
Broot->data
Cnullptr
Dnew Node(0)
Attempts:
3 left
💡 Hint
Common Mistakes
Pushing root->data instead of root pointer.
Pushing nullptr which causes runtime errors.
3fill in blank
hard

Fix 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'
Ahd
Bnode->data
Cnode
DtopViewMap
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for node->data instead of hd in the map.
Using the map itself as a key.
4fill in blank
hard

Fill 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'
A-
B+
C*
D/
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.
5fill in blank
hard

Fill 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'
Apair
Bsecond
Croot
Dfirst
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.