Write the recursive Inorder, Preorder and Postorder tree traversal algorithms.
Q.) Write the recursive Inorder, Preorder and Postorder tree traversal algorithms.
Subject: Data StructuresInorder Traversal:
void inorder(Node* root) {
if (root == NULL) {
return;
}
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}
Preorder Traversal:
void preorder(Node* root) {
if (root == NULL) {
return;
}
cout << root->data << " ";
preorder(root->left);
preorder(root->right);
}
Postorder Traversal:
void postorder(Node* root) {
if (root == NULL) {
return;
}
postorder(root->left);
postorder(root->right);
cout << root->data << " ";
}
Here's how these algorithms work:
Inorder Traversal:
- If the current node is not
NULL
, recursively callinorder()
on its left child. - Print the data of the current node.
- Recursively call
inorder()
on its right child.
Preorder Traversal:
- If the current node is not
NULL
, print the data of the current node. - Recursively call
preorder()
on its left child. - Recursively call
preorder()
on its right child.
Postorder Traversal:
- If the current node is not
NULL
, recursively callpostorder()
on its left child. - Recursively call
postorder()
on its right child. - Print the data of the current node.
These algorithms have a time complexity of O(n)
, where n
is the number of nodes in the tree. They are essential tree traversal techniques used in various applications, such as printing the elements of a tree, searching for a specific node, and calculating the height or size of a tree.