0% found this document useful (0 votes)
22 views2 pages

Lab 24

This document contains code for traversing a binary tree using preorder, inorder, and postorder traversal methods. The code defines a Node struct and functions to print the traversals. It then builds a sample binary tree and calls the print functions to output the traversals.

Uploaded by

SUJAL GUPTA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views2 pages

Lab 24

This document contains code for traversing a binary tree using preorder, inorder, and postorder traversal methods. The code defines a Node struct and functions to print the traversals. It then builds a sample binary tree and calls the print functions to output the traversals.

Uploaded by

SUJAL GUPTA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

/*LAB 24

Program for Binary tree and traversals*/


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

struct Node {
int data;
struct Node* left;
struct Node* right;
Node(int val){
data=val;
left=NULL;
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);
}
int main()
{
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


1 2 4 5 3
Inorder traversal of binary tree is
4 2 5 1 3
Postorder traversal of binary tree is
4 5 2 3 1

You might also like