Lesson 3 of 14
Preorder Traversal
Preorder Traversal
Preorder: current node → left subtree → right subtree
4
/ \
2 6
/ \ / \
1 3 5 7
Preorder visits: 4 2 1 3 6 5 7
Notice: the root comes first. Preorder is useful for copying a tree — if you insert nodes into a new tree in preorder, you get the same structure. It is also used in expression trees where operators precede their operands.
Implementation
void preorder(struct Node *root) {
if (root == NULL) return;
printf("%d\n", root->val); // visit root first
preorder(root->left);
preorder(root->right);
}
Compare with inorder: the only difference is where the printf line appears — before or after the recursive calls.
Your Task
Implement void preorder(struct Node *root) that prints each node's value, visiting the current node first, then left, then right.
TCC compiler loading...
Loading...
Click "Run" to execute your code.