Tree Lab No 7
Tree Lab No 7
Faculty of Engineering
Objectives
The purpose of this lab session is to understand the implementation of traversal algorithms for binary
trees.
Introduction
The binary tree – a tree in which each node has at most two descendants – is very often encountered in
applications. The two descendants are usually called the left and right children.
Tasks:
1. Write a C++ program to create a binary tree and traverse the binary tree in
a) Preorder
b) Inorder and
c) Postorder
struct Node {
int data;
Node* left;
Node* right;
};
int main() {
// Create the root node
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
return 0;
}
Output:
2: Write C++ program to insert your contact number in such a way that inorder traversal of binary search tree gives
your exact contact number. Also draw its logical representation.
Code: #include <iostream>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
};
int main() {
Node* root = nullptr;
return 0;
}
Output:
Logical representation
7
/\
4 9
/\ \
2 5 8
/\ \
1 3 0
\
6