PRE - Order - Traversal BST
PRE - Order - Traversal BST
#include <stdio.h>
#include <stdlib.h>
int main()
{
Node* root = NULL;
int choice, value;
do {
printf("\n1. Insert element\n");
printf("2. Preorder Traversal\n");
printf("0. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the value to insert: ");
scanf("%d", &value);
root = insert(root, value);
break;
case 2:
printf("Preorder traversal: ");
preorderTraversal(root);
printf("\n");
break;
case 0:
printf("Exiting program.\n");
break;
default:
printf("Invalid choice. Please try again.\n");
}
} while (choice != 0);
return 0;
}
Node* createNode(int data) {
Node* newNode = ( Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
return root;
}
🔹 Definition:
Pre-order traversal is a type of depth-first traversal where
the nodes are visited in the following order:
Root → Left → Right
This means:
1. Visit the current node (root)
2. Traverse the left subtree recursively
3. Traverse the right subtree recursively
🔹 Steps:
Given a binary tree:
mathematica
Copy code
A
/\
B C
/\ \
D E F
🔹 Pre-order Traversal:
Start at root A → print A
Move to left child B → print B
Move to B's left child D → print D
Back to B, move to right child E → print E
Back to root A, move to right child C → print C
Move to C's right child F → print F
🔹 Output:
ABDECF