Data Structures and Algorithms Lab Journal - Lab 8
Data Structures and Algorithms Lab Journal - Lab 8
Enrollment #: 01-235171-050
Class/Section: BS-IT(3B)
Objective
This is a lab session designed for ‘Binary Tree’ data structure and aims to enhance the
understanding of types of binary trees and their traversals.
Task 1 :
Give answers to the following.
1 For the following tree, find output of the given traversal function.
.
void Traversal(Node* temp, int
count)
{
if(temp!=NULL) {
if (count%2 == 0)
cout<<temp->data;
count++;
Traversal(temp->left, count);
Traversal(temp->right, count);
}
}
ii. A complete binary tree has 25 nodes. What is depth of the given tree?
ANSWER: 4
Task 2 :
Exercise 1
An effective way to represent Mathematical expressions is using the binary trees. The
following algorithm can be employed to generate an expression tree from a given postfix
expression.
};
TNode * constructTree(string postfix)
Implement the function to convert a given
postfix expression into an expression tree. Use the stack class in the STL library and create a
Stack as follows.
CODE :
#include<iostream>
#include<conio.h> using namespace std; struct et
if (!isOperator(postfix[i]))
{ t = newNode(postfix[i]);
st.push(t); } else
{ t = newNode(postfix[i]); t1
= st.top(); st.pop(); t2
= st.top(); st.pop(); t-
>right = t1; t->left =
t2; st.push(t);
}
}
t = st.top();
st.pop(); return t; }
int main()
{ char postfix[] = "ab+ef*g*-"; et* r =
constructTree(postfix);
printf("infix expression is \n");
inorder(r); return 0;
}
Exercise 2
Create the following tree and implement the following functions and give their outputs:
CODE :
#include <conio.h>
#include <iostream> using
namespace std; struct
node
{ int data; struct node*
left; struct node*
right;
}; int getLeafCount(struct node*
node->data = data;
node->left = NULL; node-
>right = NULL;
return(node);
} int
main()
{ struct node *root = newNode(1);
root->left = newNode(2); root-
>right = newNode(3); root-
>left->left = newNode(4); root-
>left->right = newNode(5);
cout << "Leaf count of the tree is : " << getLeafCount(root) << endl;
cout << "Non Leaf count of the tree is : " << countNonleaf(root);
return 0;
}
OUTPUT :
Implement the given exercises and get them checked by your instructor. If you are unable to
complete the tasks in the lab session, deposit this journal alongwith your programs (printed
or handwritten) before the start of the next lab session.
2. Exercise 2
+++++++++++++++++++++++++