Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
25 views3 pages

OOLP10

Uploaded by

Rahul Jain
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)
25 views3 pages

OOLP10

Uploaded by

Rahul Jain
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/ 3

Program:- Binary Tree Traversal

// Tree traversal in C++

#include <iostream>
using namespace std;

struct Node {
int data;
struct Node *left, *right;
Node(int data) {
this->data = data;
left = right = NULL;
}
};

// Preorder traversal
void preorderTraversal(struct Node* node) {
if (node == NULL)
return;

cout << node->data << "->";


preorderTraversal(node->left);
preorderTraversal(node->right);
}

// Postorder traversal
void postorderTraversal(struct Node* node) {
if (node == NULL)
return;

postorderTraversal(node->left);
postorderTraversal(node->right);
cout << node->data << "->";
}

// Inorder traversal
void inorderTraversal(struct Node* node) {
if (node == NULL)
return;

inorderTraversal(node->left);
cout << node->data << "->";
inorderTraversal(node->right);
}

int main() {
struct Node* root = new Node(1);
root->left = new Node(12);
root->right = new Node(9);
root->left->left = new Node(5);
root->left->right = new Node(6);

cout << "Inorder traversal ";


inorderTraversal(root);
cout << "\nPreorder traversal ";
preorderTraversal(root);

cout << "\nPostorder traversal ";


postorderTraversal(root);
return 0;
}
Output: -

You might also like