Created: 2023-11-07 00:48
Status: #concept
Subject: Programming
Tags: Tree Binary Tree Breadth-First Search Algorithm
Depth-First Search
Pre-order Traversal (current-left-right)
Visit the current node before visiting any nodes inside the left or right subtrees.
void preOrder(Node node) {
if (node != NULL) {
printf("%d ", node->elem);
preOrder(node->LC);
preOrder(node->RC);
}
}
In-order Traversal (left-current-right)
Visit the current node after visiting all nodes of its left subtree - then visit the right subtree.
This is the preferred way as it orders elements in a balanced Binary Tree.
void inOrder(Node node) {
if (node != NULL) {
inOrder(node->LC);
printf("%d ", node->elem);
inOrder(node->RC);
}
}
Post-order Traversal (left-right-current)
We visit the left & right subtrees before visiting the current node.
void postOrder(Node node) {
if (node != NULL) {
postOrder(node->LC);
postOrder(node->RC);
printf("%d ", node->elem);
}
}