Write the recursive Inorder, Preorder and Postorder tree traversal algorithms.


Q.) Write the recursive Inorder, Preorder and Postorder tree traversal algorithms.

Subject: Data Structures

Inorder 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:

  1. If the current node is not NULL, recursively call inorder() on its left child.
  2. Print the data of the current node.
  3. Recursively call inorder() on its right child.

Preorder Traversal:

  1. If the current node is not NULL, print the data of the current node.
  2. Recursively call preorder() on its left child.
  3. Recursively call preorder() on its right child.

Postorder Traversal:

  1. If the current node is not NULL, recursively call postorder() on its left child.
  2. Recursively call postorder() on its right child.
  3. 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.