Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a new tree node with given value.
DSA C
struct TreeNode* newNode(int val) {
struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->val = [1];
node->left = NULL;
node->right = NULL;
return node;
}Attempts:
3 left
💡 Hint
Common Mistakes
Assigning NULL or 0 instead of the input value.
Using the wrong variable name.
✗ Incorrect
The new node's value should be set to the input parameter 'val'.
2fill in blank
mediumComplete the code to check if the current node is NULL during serialization.
DSA C
void serialize(struct TreeNode* root, FILE* fp) {
if (root == [1]) {
fprintf(fp, "# ");
return;
}
fprintf(fp, "%d ", root->val);
serialize(root->left, fp);
serialize(root->right, fp);
}Attempts:
3 left
💡 Hint
Common Mistakes
Checking 'root == 0' which is less clear in C.
Checking 'root == root' which is always true.
✗ Incorrect
We check if the node pointer is NULL to mark the end of a branch.
3fill in blank
hardFix the error in reading the next token during deserialization.
DSA C
struct TreeNode* deserialize(FILE* fp) {
char val[10];
if (fscanf(fp, "%s", val) != 1) {
return NULL;
}
if (val[0] == [1]) {
return NULL;
}
struct TreeNode* node = newNode(atoi(val));
node->left = deserialize(fp);
node->right = deserialize(fp);
return node;
}Attempts:
3 left
💡 Hint
Common Mistakes
Checking for '0' or space instead of '#'.
Using incorrect character comparison.
✗ Incorrect
The '#' character marks a NULL node in serialization format.
4fill in blank
hardFill both blanks to complete the preorder traversal for serialization.
DSA C
void serialize(struct TreeNode* root, FILE* fp) {
if (root == [1]) {
fprintf(fp, "# ");
return;
}
fprintf(fp, "%d ", root->val);
serialize(root->[2], fp);
serialize(root->right, fp);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'root' instead of 'NULL' in the if condition.
Recursing on 'right' instead of 'left' first.
✗ Incorrect
Check if root is NULL, then recurse on root->left child.
5fill in blank
hardFill all three blanks to complete the deserialize function correctly.
DSA C
struct TreeNode* deserialize(FILE* fp) {
char val[10];
if (fscanf(fp, "%s", val) != 1) {
return [1];
}
if (val[0] == [2]) {
return NULL;
}
struct TreeNode* node = newNode(atoi([3]));
node->left = deserialize(fp);
node->right = deserialize(fp);
return node;
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning 'node' instead of NULL on fscanf failure.
Using wrong variable in atoi.
✗ Incorrect
Return NULL if no input, check for '#' to mark NULL node, and convert 'val' to int.
