Which of the following best explains why trees are preferred over arrays or linked lists for representing hierarchical data?
Think about how data with multiple levels and branches is organized.
Trees naturally represent hierarchical data with nodes having multiple children, unlike arrays or linked lists which are linear structures.
Given the following tree node structure and traversal code, what is the output?
struct Node {
int data;
struct Node* left;
struct Node* right;
};
void preorder(struct Node* root) {
if (root == NULL) return;
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
}
int main() {
struct Node n1 = {1, NULL, NULL};
struct Node n2 = {2, NULL, NULL};
struct Node n3 = {3, &n1, &n2};
preorder(&n3);
return 0;
}Preorder traversal visits root first, then left subtree, then right subtree.
The preorder traversal prints the root node data first, then recursively visits left and right children.
What error will the following code cause when inserting a new node into a binary tree?
struct Node {
int data;
struct Node* left;
struct Node* right;
};
void insert(struct Node* root, int value) {
if (value < root->data) {
if (root->left == NULL) {
root->left = malloc(sizeof(struct Node));
root->left->data = value;
root->left->left = NULL;
root->left->right = NULL;
} else {
insert(root->left, value);
}
} else {
if (root->right == NULL) {
root->right = malloc(sizeof(struct Node));
root->right->data = value;
root->right->left = NULL;
root->right->right = NULL;
} else {
insert(root->right, value);
}
}
}Check what happens when root->left or root->right is NULL before assignment.
The code tries to assign data to root->left->data without allocating memory for root->left, causing a crash.
What is the output of the following code when searching for value 5?
struct Node {
int data;
struct Node* left;
struct Node* right;
};
int search(struct Node* root, int value) {
if (root == NULL) return 0;
if (root->data == value) return 1;
if (value < root->data) return search(root->left, value);
else return search(root->right, value);
}
int main() {
struct Node n1 = {3, NULL, NULL};
struct Node n2 = {7, NULL, NULL};
struct Node n3 = {5, &n1, &n2};
int found = search(&n3, 5);
printf("%d", found);
return 0;
}Search returns 1 if value is found, 0 otherwise.
The value 5 is at the root node, so search returns 1 and prints it.
Which statement best explains why linked lists and arrays are inefficient for representing multi-branch hierarchical data compared to trees?
Consider how many children a node can have and how that fits into linear vs hierarchical structures.
Linked lists and arrays are linear and do not support multiple branches per node easily, requiring complex workarounds, while trees naturally support multi-branch nodes.
