struct Node {
int value;
struct Node* left;
struct Node* right;
};
void preorder(struct Node* root) {
if (root == NULL) return;
printf("%d ", root->value);
preorder(root->left);
preorder(root->right);
}
int main() {
struct Node n3 = {3, NULL, NULL};
struct Node n4 = {4, NULL, NULL};
struct Node n2 = {2, &n3, &n4};
struct Node n1 = {1, NULL, NULL};
struct Node root = {0, &n1, &n2};
preorder(&root);
return 0;
}Preorder traversal prints the root node first, then recursively visits the left child, then the right child. So the order is 0 (root), 1 (left child), 2 (right child), then 3 and 4 (children of 2).
Trees naturally represent hierarchical data with parent-child relationships and allow efficient traversal of all nodes. Arrays and linked lists are linear and do not capture hierarchy well. Stacks are for last-in-first-out access, not hierarchy.
struct Node {
int value;
struct Node* next;
};
int main() {
struct Node n1 = {1, NULL};
struct Node n2 = {2, NULL};
struct Node n3 = {3, NULL};
n1.next = &n2;
n2.next = &n3;
// Trying to represent a tree hierarchy here
return 0;
}A linked list node has only one pointer to the next node, so it cannot represent multiple children of a node in a hierarchy. Trees require nodes to have multiple pointers (e.g., left and right child) to represent branching.
int tree[] = {10, 20, 30, 40, 50, 60, 70}; int main() { printf("%d %d %d", tree[0], tree[1], tree[2]); return 0; }
In a binary tree stored as an array in level order, index 0 is the root, index 1 is the left child, and index 2 is the right child. So printing these indices outputs 10 20 30.
Trees naturally support multiple children per node and hierarchical traversal, making them ideal for complex hierarchies. Arrays and linked lists are linear and cannot easily represent branching structures.
