Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare the structure for a binary tree node.
DSA C
struct Node {
int data;
struct Node* [1];
struct Node* right;
};Attempts:
3 left
💡 Hint
Common Mistakes
Using 'child' or 'next' instead of 'left' for the left child pointer.
✗ Incorrect
The left child pointer in a binary tree node is usually named 'left'.
2fill in blank
easyFill the blanks to complete the main function that initializes and calls the top view utility.
DSA C
int main() {
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
int minHd = 0, maxHd = 0;
int visited[100] = {0};
topViewUtil(root, [1], &minHd, &maxHd, visited);
return [2];
}
struct Node* newNode(int data) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 1 instead of 0 for horizontal distance or return value.
✗ Incorrect
The initial horizontal distance for the root is 0. The main function should return 0 upon successful execution.
3fill in blank
mediumComplete the code to create a new node with given data.
DSA C
struct Node* newNode(int data) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = NULL;
node->[1] = NULL;
return node;
}Attempts:
3 left
💡 Hint
Common Mistakes
Initializing wrong pointer like 'parent' or 'next' instead of 'right'.
✗ Incorrect
The right child pointer must be initialized to NULL when creating a new node.
4fill in blank
mediumComplete the code to print the level order traversal of the binary tree using a queue.
DSA C
void topView(struct Node* root) {
if (root == NULL) return;
struct Queue* q = createQueue();
enqueue(q, root);
while (!isEmpty(q)) {
struct Node* temp = dequeue(q);
printf("%d ", temp->data);
if (temp->left) enqueue(q, temp->[1]);
if (temp->right) enqueue(q, temp->right);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'temp->parent' or 'temp->next' instead of 'temp->left'.
✗ Incorrect
In level order traversal using queue, enqueue the left child first, then the right child.
5fill in blank
hardFill both blanks to complete the function that stores the first node at each horizontal distance for top view.
DSA C
void topViewUtil(struct Node* root, int hd, int* minHd, int* maxHd, int* visited) {
if (root == NULL) return;
if(hd < *minHd) *minHd = hd;
if(hd > *maxHd) *maxHd = hd;
topViewUtil(root->[1], hd - 1, minHd, maxHd, visited);
if (visited[hd + 50] == 0) {
printf("%d ", root->data);
visited[hd + 50] = 1;
}
topViewUtil(root->[2], hd + 1, minHd, maxHd, visited);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'parent' or 'child' instead of 'left' or 'right'.
✗ Incorrect
Traverse left child with 'root->left' (decrement hd) and right child with 'root->right' (increment hd).
