Tree traversal refers to visiting every node in a tree systematically. It is essential for performing operations such as printing, searching, and modifying nodes.
DFS explores as far as possible along each branch before backtracking.
// Example: Inorder traversal (C++)
void inorder(Node* root) {
if (root != NULL) {
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}
}
Visits nodes level by level from top to bottom using a queue.
// Example: Level Order Traversal
void levelOrder(Node* root) {
if (root == NULL) return;
queue q;
q.push(root);
while (!q.empty()) {
Node* current = q.front();
q.pop();
cout << current->data << " ";
if (current->left) q.push(current->left);
if (current->right) q.push(current->right);
}
}
Tree traversal algorithms are essential for processing tree data structures. Choosing the right traversal depends on the specific operation and the structure of the tree.
Take quizzes related to this topic and see where you stand!
Start Quiz Now