DEV Community

Mujahida Joynab
Mujahida Joynab

Posted on

Preorder Traversal

Pre order : Root Left Right
In order : Left Root Right
Post order : Left Right Root

Pre -> before
In -> Middle
Post -> After

Code
We will implement it using recursion

#include <bits/stdc++.h>
using namespace std;

class Node
{
public:
    int val;
    Node *right;
    Node *left;
    Node(int value)
    {
        this->val = value;
        this->right = NULL;
        this->left = NULL;
    }
};

void preorder(Node *root)
{
    if (root == NULL)
        return;
    cout << root->val << " "; // root
    preorder(root->left);     // left
    preorder(root->right);    // right
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    Node *root = new Node(10);
    Node *a = new Node(12);
    Node *b = new Node(20);
    Node *c = new Node(30);
    Node *d = new Node(40);
    Node *e = new Node(50);
    Node *f = new Node(60);

    root->left = a;
    root->right = b;
    a->left = c;
    b->left = d;
    b->right = e;

    preorder(root);
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more