Professional Documents
Culture Documents
Enrollment #: 01-134181-026
Class/Section: BS (CS)-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 :
ii. A c o m p l e t e b i n a r y t r e e h a s 2 5 n o d e s . W h a t i s d e p t h o f t h e g i v e n t r e e ?
Depth: 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.
on the stack
5. If the symbol is an operator
T2 = Pop()
T1 = Pop()
Attach T1 to the left and T2 to the right of Curr
Set the operator as data member of the node Curr
Push Curr (with child nodes attached) onto the stack
6. Repeat Steps 1-5 till end of expression
7. Pop the (only remaining) node from the stack which is a pointer to the root of the
expression tree.
};
Implement the function TNode * constructTree(string postfix) 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
TNode.h
#pragma once
#include<iostream>
#include<conio.h>
TNode *right;
TNode(char value)
{
data = value;
left = right = NULL;
}
};
main.cpp
#pragma once
#include "TNode.h"
#include <stack>
#include <string>
int main()
{
string s = "ab+ef*g*-";
TNode *root = constructTree(s);
cout << "\n\n\n\n\n\n\n\n\n\n\t\t\t EXPRESSION: ";
postorder(root);
_getch();
return 0;
}
if (!isoperator(postfix[i]))
{
curr = new TNode(postfix[i]);
s.push(curr);
}
else
{
curr = new TNode(postfix[i]);
curr->right = s.top();
s.pop();
curr->left = s.top();
s.pop();
s.push(curr);
}
i++;
}
curr = s.top();
s.pop();
return curr;
}
OUTPUT :
Exercise 2
Create the tree following tree and implement the following functions and give their outputs:
a) bool search(TNode *root, int key) ; //finds if a given key value exits in the tree
b) int count_leaf(TNode *root) ; //returns the total number of leaf nodes in the tree
c) int count_nonleaf(TNode *root) ; //returns the total number of non-leaf nodes in the
tree
d) bool isleaf(TNode *root, int value) ; //checks if the queried node is a leaf
a) bool search(TNode *root, int key) ;
else
{
flag = search(root->right, key);
flag = search(root->left, key);
}
}
{
bool flag = false;
if (t == NULL)
return false;
else if (t->data == value)
{
if (t->left == NULL && t->right == NULL)
{
return true;
}
else
{
return false;
}
}
else
{
flag = isleaf(t->right, value);
flag = isleaf(t->left, value);
}
}
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
+++++++++++++++++++++++++