Skip to main content

Tree in C++

 

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

struct node
{
    int data;
    struct node *left;
    struct node *right;
};

struct node *create(int val)
{
    node *n = new node;
    n->data = val;
    n->left = NULL;
    n->right = NULL;
    return n;
}
void preorder(struct node *root)
{
    if (root != NULL)
    {
        cout << root->data << " ";
        preorder(root->left);
        preorder(root->right);
    }
}
void postorder(struct node *root)
{
    if (root != NULL)
    {
        postorder(root->left);
        postorder(root->right);
        cout << root->data << " ";
    }
}
void inorder(struct node *root)
{
    if (root != NULL)
    {
        inorder(root->left);
        cout << root->data << " ";
        inorder(root->right);
    }
}
int main()
{
    node *root = create(1);
    node *a = create(4);
    node *a1 = create(3);
    node *a2 = create(9);
    node *a3 = create(5);
    root->left = a;
    root->right = a1;
    root->left->left = a2;
    root->left->right = a3;

    cout << "Preorder: ";
    preorder(root);
    cout << endl;
    cout << "Posteorder: ";
    postorder(root);
    cout << endl;
    cout << "Inorder: ";
    inorder(root);

    return 0;
}


Comments