A tree is a hierarchical data structure that represents a collection of nodes, where one node is designated as the root, and the rest are connected via edges. Trees are widely used in scenarios like organizing data hierarchically (e.g., file systems) and implementing various algorithms efficiently (e.g., searching and sorting).
Traversal refers to visiting each node in the tree in a specific order. There are two primary types:
Inorder Traversal (Left → Root → Right):
C++ Implementation:
void inorder(TreeNode* root) {
if (root == nullptr) return;
inorder(root->left); // Traverse left subtree
cout << root->data << " "; // Visit root
inorder(root->right); // Traverse right subtree
}
Preorder Traversal (Root → Left → Right):
C++ Implementation:
void preorder(TreeNode* root) {
if (root == nullptr) return;
cout << root->data << " "; // Visit root
preorder(root->left); // Traverse left subtree
preorder(root->right); // Traverse right subtree
}
Postorder Traversal (Left → Right → Root):
C++ Implementation:
void postorder(TreeNode* root) {
if (root == nullptr) return;
postorder(root->left); // Traverse left subtree
postorder(root->right); // Traverse right subtree
cout << root->data << " "; // Visit root
}
Algorithm:
C++ Implementation:
#include <iostream>
#include <queue>
using namespace std;
struct TreeNode {
int data;
TreeNode* left;
TreeNode* right;
TreeNode(int value) : data(value), left(nullptr), right(nullptr) {}
};
void levelOrder(TreeNode* root) {
if (root == nullptr) return;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* current = q.front();
q.pop();
cout << current->data << " ";
if (current->left) q.push(current->left);
if (current->right) q.push(current->right);
}
}
int main() {
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
cout << "Level-Order Traversal: ";
levelOrder(root);
return 0;
}
| Feature | DFS | BFS |
|---|---|---|
| Traversal Order | Explores depth first. | Explores level by level. |
| Data Structure | Uses recursion or a stack. | Uses a queue. |
| Memory Usage | May use less memory if tree is shallow. | May use more memory for wide trees. |
| Use Case | Finding paths, evaluating trees. | Shortest path, exploring breadth. |
Let’s consider this tree:
1
/ \
2 3
/ \ / \
4 5 6 7
DFS Traversals:
4 2 5 1 6 3 71 2 4 5 3 6 74 5 2 6 7 3 1BFS Traversal:
1 2 3 4 5 6 7This summary should help you understand tree structures and traversal techniques in an intuitive and detailed way! 😊
Open this section to load past papers