Preorder Tree Traversal in Binary Tree In C++

Preorder Tree Traversal

Preorder traversal is a depth first algorithm. There are three types of traversals in tree: Preorder, Inorder, Postorder. In this article, preorder tree traversal is performed using recursion.

C++ Program To Find Preorder Of a Tree

More About Preorder Traversal

  1. We first print the value of the node,them move to the left subtree and finally to the right subtree.
  2. If we need to explore more about the node itself before inspecting its leaves, we use preorder traversal.
  3. Preorder traversal is used to find the prefix expression of an expression tree.
Example for preorder traversal in binary tree

Steps To Find Preorder Traversal:

  1. Print the root node and traverse the left subtree.
  2. After printing 12, move to the left.
  3. 8 is printed and we move to the left subtree.
  4. Print 5 and move back,
  5. Since there is only 1 right child 13 is printed and we move to the right subtree.
  6. 54 and 18 are printed.
Orientation Of Stack - C++ Program To Find Preorder Traversal

Algorithm To Find Preorder Traversal:

  1. If root is NULL, return NULL.
  2. Print the node.
  3. Visit left subtree.
  4. Visit right subtree.

Code:

#include <bits/stdc++.h>
using namespace std;
class Tree {
    public:
        int data;
        Tree* left = NULL,*right = NULL;
        // Constructor initialised
        Tree(int x) {
            data = x;
            left = NULL;
            right = NULL;
        }
};
void preorder_traversal (Tree *root) {
    if (root == NULLreturn;
    // Print the data
    cout << root -> data << ” “;
    // Visit Left subtree
    preorder_traversal(root -> left);
    // Visit right subtree
    preorder_traversal(root -> right);
}
int main() {
    Tree *root = new Tree(15);
    root -> left = new Tree(12);
    root -> right = new Tree(54);
    root -> left -> left = new Tree(8);
    root -> left -> right = new Tree(13);
    root -> left -> left -> left = new Tree(5);
    root -> right -> left = new Tree(18);
    preorder_traversal(root);
    return 0;
}


 

Output:

15 12 8 5 13 54 18 

 

Time Complexity To Find Preorder Traversal in Binary Tree

Time Complexity

O(n)

Space Complexity

O(h)