0% found this document useful (0 votes)
30 views

Write A Program To Demonstrate Inorder, Preorder, Postorder Treversal of A Tree

The document describes a C++ program that demonstrates inorder, preorder, and postorder tree traversal of a binary tree. It defines a Node struct with left and right pointers and functions for each traversal type. The main function builds a sample tree, calls each traversal function, and outputs the results.

Uploaded by

RITIKA SINGH
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Write A Program To Demonstrate Inorder, Preorder, Postorder Treversal of A Tree

The document describes a C++ program that demonstrates inorder, preorder, and postorder tree traversal of a binary tree. It defines a Node struct with left and right pointers and functions for each traversal type. The main function builds a sample tree, calls each traversal function, and outputs the results.

Uploaded by

RITIKA SINGH
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Write a program to demonstrate inorder, preorder, postorder

treversal of a tree.

Program:

#include <iostream>
using namespace std;
struct Node
{
    int data;
    struct Node* left, *right;
    Node(int data)
    {
        this->data = data;
        left = right = NULL;
    }
};
  
void printPostorder(struct Node* node)
{
    if (node == NULL)
        return;
    printPostorder(node->left);
    printPostorder(node->right);
    cout << node->data << " ";
}
  
void printInorder(struct Node* node)
{
    if (node == NULL)
        return;
    printInorder(node->left);
    cout << node->data << " ";
    printInorder(node->right);
}
  
void printPreorder(struct Node* node)
{
    if (node == NULL)
        return;
    cout << node->data << " ";
    printPreorder(node->left); 
    printPreorder(node->right);

{
    struct Node *root = new Node(1);
    root->left             = new Node(2);
    root->right         = new Node(3);
    root->left->left     = new Node(4);
    root->left->right = new Node(5); 
  
    cout << "\nPreorder traversal of binary tree is \n";
    printPreorder(root);
  
    cout << "\nInorder traversal of binary tree is \n";
    printInorder(root); 
  
    cout << "\nPostorder traversal of binary tree is \n";
    printPostorder(root);
  
    return 0;
}

Output:
Preorder traversal of binary tree is
12453
Inorder traversal of binary tree is
42513
Postorder traversal of binary tree is
45231

You might also like