0% found this document useful (0 votes)
26 views19 pages

DSAL Assignments 4 5 6

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

DSAL Assignments 4 5 6

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

Assignment 04 – Expression Tree and Tree Traversals

Aim: To construct an expression tree and perform recursive and non-recursive traversals.

Problem statement: To construct an Expression Tree from postfix and prefix expression.
Perform recursive and non- recursive in-order, pre-order and post-order traversals.

Objective: 1. To understand non-linear data structure: Tree.


2. To implement non-linear data structure: Tree.
3. To understand applications of Tree.

Outcome: 1. To implement expression tree.


2. To perform recursive and non-recursive traversals.
3. To understand applications of tree

Theory:

Definition of Expression Tree:


For an Algebraic expressions such as: 3 + (4 * 6) or a+b*c

The terminal nodes (leaves) of an expression tree are the variables or constants in the
expression (3,4, 6, or a, b, c). The non-terminal nodes of an expression tree are the operators (+,
-, *, /).

Notice that the parentheses which appear in equation do not appear in the tree.

Examples of Expression Tree:


Applications of Expression Tree:

1. Expression conversion i.e. to convert infix expression to postfix or prefix and vice a versa.
2. Evaluation of an infix, prefix and postfix expression.

Data Structures to Implement Expression Tree:

An arithmetic expression consists of operands (variable or constant) and operators. To construct


an expression binary tree Stack is an appropriate data structure.
In construction of expression tree process two stack as an array are declared one as operand
stack to store operand as node and other as operator stack to store operator as a node for an
infix or prefix or postfix expression.

Different type of traversals with example:

To traverse a non-empty binary tree in pre-order:

1. Visit the root.


2. Traverse the left sub tree.
3. Traverse the right sub tree.

To traverse a non-empty binary tree in in-order:


1. Traverse the left sub tree.
2. Visit the root.
3. Traverse the right sub tree.

To traverse a non-empty binary tree in post-order,


1. Traverse the left sub tree.
2. Traverse the right sub tree.
3. Visit the root.

Consider an example of an expression tree:

+ -

a b c d
1. Pre-order (Prefix) : *+ab–cd

2. In-order (Infix) : a+b*c-d

3. Post-order (postfix) : ab+cd-*

ADT of Expression Tree:

Structure: Binary_Tree ( ) is

Objects: a finite set of nodes either empty or consisting of a root node, left_Binary_Tree, and
right_Binary_Tree.

For all bt, bt1, bt2 ∈ Binary_Tree, item ∈ element


Functions:

Binary_Tree Create( )::= creates an empty binary tree

Boolean IsEmpty(bt)::= if (bt==empty binary tree) return TRUE else return FALSE

Binary_Tree MakeBT(bt1, item, bt2)::= return a binary tree whose left sub tree is bt1, whose
right sub tree is bt2, and whose root node contains the data item

Binary_Tree Lchild(bt)::= if (IsEmpty(bt)) return error else return the left sub tree of bt

Element Data(bt)::= if (IsEmpty(bt)) return error else return the data in the root node of bt

Binary_Tree Rchild(bt)::= if (IsEmpty(bt)) return error else return the right sub tree of bt

END

Algorithms:

a. Create Expression Tree:

For constructing expression tree we use a stack. We loop through input expression and do
following for every character.
1. Read an infix expression in an array and convert it to postfix and prefix. And perform following:

2. If character is operand push that into stack

3. If character is operator pop two values from stack make them its child and push current node
again.

At the end only element of stack will be root of expression tree.


b. In-order Traversal (Recursive):

1. Traverse the left sub tree, i.e. call In-order (left – sub-tree)
2. Visit the root.
3. Traverse the right sub tree, i.e. call In-order (right – sub-tree)

c. Pre-order Traversal (Recursive):

1. Visit the root.


2. Traverse the left sub tree, i.e. call Pre-order (left – sub-tree)
3. Traverse the right sub tree, i.e. call Pre-order (right – sub-tree)

d. Post-order Traversal (Recursive):

1. Traverse the left sub tree, i.e. call Post-order (left – sub-tree)
2. Traverse the right sub tree, i.e. call Post-order (right – sub-tree)
3. Visit the root.

e. In-order Traversal (Non- recursive):

1. Create an empty stack S.


2. Initialize current node as root
3. Push the current node to S and set current = current->left until current is NULL
4. If current is NULL and stack is not empty then
a. Pop the top item from stack.
b. Print the popped item, set current = popped_item->right
c. Go to step 3.
5. If current is NULL and stack is empty then stop.

f. Pre-order Traversal (Non – recursive):

1. Create an empty stack S and push root node to stack.

2. Do following while S is not empty.

a. Pop an item from stack and print it.

b. Push right child of popped item to stack

c. Push left child of popped item to stack


3. If stack is empty, then stop.

g. Post-order Traversal (Non – recursive):

1. Create an empty stack S


2. Do following while root is not NULL
a. Push root's right child and then root to stack.
b. Set root as root's left child.
3. Pop an item from stack and set it as root.
a. If the popped item has a right child and the right child is at top of stack, then
remove the right child from stack, push the root back and set root as root's right child.
b. Else print root's data and set root as NULL.
4. Repeat steps 3.a and 3.b while stack is not empty, then stop.

Test Cases / Validation:

Validations:

1. Identification of symbol as operator or operand.


2. Postfix and prefix expressions can be of char or int data type

Test Cases

1. Operator precedence and associativity


2. Appropriate error messages for wrong input

Infix Prefix
A * (B + C) / D /*A+BCD

Infix Postfix
3 + (8 * 7) – 2 387*+2-

FAQS:
1. What is tree? What are properties of trees?
2. What is Binary tree, Binary search tree, Expression tree & General tree?
3. What are the members of structure of tree & what is the size of structure?
4. What are rules to construct binary tree?
5. What is preorder, post-order, in-order traversal?
6. Difference between recursive & Non-recursive traversal?
7. What are rules to construct binary search tree?
8. What are rules to construct expression tree?
9. How binary tree is constructed from its traversals?
5. Binary Tree

AIM: Create Binary Tree (BT) and perform following operations:


a. Insert
b. Display
c. Depth of a tree
d. Display leaf-nodes
e. Create a copy of a tree

OBJECTIVE:
1. To understand the concept of binary tree as a data structure.
2. Applications and Operations of BT.

THEORY:
A binary tree is made of nodes, where each node contains a "left" reference, a "right"
reference, and a data element. The topmost node in the tree is called the root.

Definition: A binary tree is a finite set of elements that is either empty or is partitioned into
three disjoint subsets. The first subset contains a single element called the root of the tree.
The other two subsets are themselves binary trees, called the left and right subtrees of the
original tree. Conventional method of picturing binary tree

Every node (excluding a root) in a tree is connected by edge from exactly one other node.
This node is called a parent. On the other hand, each node can be connected to arbitrary
number of nodes, called children. Nodes with no children are called leaves, or external
nodes. Nodes which are not leaves are called internal nodes. Nodes with the same parent
are called siblings.

Advantages of BT:

Trees are so useful and frequently used, because they have some very serious
advantages:

 BT reflect structural relationships in the data


 BT are used to represent hierarchies
 BT are very flexible data, allowing to move subtrees around with minimum effort

Traversals

A traversal is a process that visits all the nodes in the tree. Since a tree is a nonlinear data
structure, there is no unique traversal. Two broad categories of traversals are

 depth-first traversal
 breadth-first traversal

There are three different types of depth-first traversals:

 PreOrder traversal - visit the parent first and then left and right children
 InOrder traversal - visit the left child, then the parent and the right child
 PostOrder traversal - visit left child, then the right child and then the parent

As an example consider the following tree and its four traversals:

PreOrder - 8, 5, 9, 7, 1, 12, 2, 4, 11, 3


InOrder - 9, 5, 1, 7, 2, 12, 8, 4, 3, 11
PostOrder - 9, 1, 2, 12, 7, 5, 3, 11, 4, 8
LevelOrder - 8, 5, 4, 9, 7, 11, 1, 12, 3, 2

There is only one kind of breadth-first traversal--the level order traversal. This traversal
visits nodes by levels from top to bottom and from left to right.
ALGORITHM:

Insert Node:

Insertion operation means inserting a new node into any position of the binary tree.
The insertion operation can take place in any one of the following two positions

1. At the external node


2. At internal node

Here , Algorithm of only insertion of node as a external node is considered. The


insertion operation involves the following steps

1. Search for a node after which an insertion has to be made


2. Establish a link for the new node

Steps:

1. Accept the KEY (or data item) which has to be searched in a BT after which
the new data item has to be placed
2. Accept the item to be inserted, ITEM
3. Start from the ROOT node, search KEY in the binary tree. The address of
the node with KEY as the data will be in the ptr.
4. Check whether ptr contains NULL or not. If ptr is NULL then Search is
Unsuccessful.
5. Otherwise

a. Node with data item KEY is there in the binary tree (i.e in ptr)
b. Now check whether the left child of ptr is empty or the right child of ptr
is empty. If the left child of the ptr is empty then do steps (i) to (v)

(i) Allocate memory space for the new node (say new)
(ii) Place the item to be inserted (ITEM) in the new node.
(iii) Make the left child and right child fields of the new node to be
NULL
(iv) Make the new node as left child of ptr.

c. Otherwise check whether the right child of ptr is empty. If the right
child of the ptr is empty then do steps (i) to (v)

(i) Allocate memory space for the new node (say new)
(ii) Place the item to be inserted (ITEM) in the new node.
(iii) Make the left child and right child fields of the new node to be
NULL
(iv) Make the new node as right child of ptr.

d. Otherwise Print ―Insertion is not possible. The KEY node already has
a child
6. Stop

Display:

In order to display content of each node in exactly once, a BT can be traversed in


either Pre-Order, Post- Order, In-Order.
Here Pre-order Traversal is considered

1. Visit the root node R First


2. Then visit the left sub tree of R in Pre-Order fashion
3. Finally, visit the right sub tree of R in Pre-Order fashion

Depth of a Tree:

This function finds the depth of the linked binary tree.

1. Start from the ROOT node and store the address of the root node in ptr.
2. Check whether ptr contains NULL or not. If ptr is NULL then tree is empty.
3. Otherwise

a. Get the height of left sub tree, say leftHeight.


b. Get the height of right sub tree, say rightHeight.
c. Take the Max(leftHeight, rightHeight) and add 1 for the root and return.
d. Call recursively.

Display Leaf-Nodes:

This function displays all the leaf nodes in the linked binary tree.

1. Start from the ROOT node and store the address of the root node in ptr.
2. Check whether ptr contains NULL or not. If ptr is NULL then tree is empty.
3. Otherwise

a. Check whether the left child and right child of ptr are empty or not. If the
left child and right child of ptr are NULL then display the content of the
node.
b. Traverse the left subtrees and the right subtrees and repeat step a for all
the nodes.

4. Stop

Create a Copy of a Tree:

This function will make a copy of the linked binary tree. The function should allocate
memory for necessary nodes and copy respective contents in it.

1. Start from the ROOT node. The address of the root node will be in the ptr. Let
newroot be the root of the new tree after the copy.
2. Check whether ptr contains NULL or not. If ptr is NULL then newroot = NULL
3. Otherwise

(i) Allocate memory space for the new node


(ii) Copy the data from current node from the old tree to node in
the new tree.
(iii) Traverse each node in the left subtrees from the old tree and
repeat step (i) and (ii).
(iv) Traverse each node in the right subtrees from the old tree and
repeat step (i) and (ii).

4. Stop

INPUT:
Test Case O/P
Tree Empty Display message ―Tree Empty‖
Insertion is not possible. The KEY node already has a child
Binary Tree
OUTPUT:
Height of a Binary Tree

FAQ:

1. What is a Binary Tree?


2. List the different types of Binary Tree?
3. List the different methods of visiting the nodes of a binary tree?
4. What are the various operations that can be performed on Binary Tree?
5. List the different methods of converting general tree to Binary Tree.
6. Threaded Binary Tree

1 Title Assignment 6: Threaded Binary Tree (TBT).


2. Aim To implement In-order Threaded Binary Tree (TBT)
3. Problem To implement In-order TBT and to perform In-order, and Pre-order
statement traversals.

4. Objective 1. To understand construction of TBT.


2. To implement In-order TBT.
3. To understand In-order, and Pre-order traversals of TBT.
4. To understand pros/cons of TBT over Binary Tress.

5. Outcome 1. To implement In-order TBT


2. To Perform In-Order and Preorder Traversal of TBT

6. Theory Issues with regular Binary Tree Traversals:


1. The storage space required for stack and queue is large.
2. The majority of pointers in any binary tree are NULL. For example, a
binary tree with n nodes has n+1 NULL pointers and these were
wasted.
3. It is difficult to find successor node (Pre-order, In-order and Post-order
successors) for a given node.
Motivation for Threaded Binary Trees:
To solve these problems, one idea is to store some useful information in
NULL pointers. In the traversals of regular binary tree, stack/queue is
required to record the current position in order to move to right subtree
after processing the left subtree. If the null links are replaced with useful
information, then storing current position in order to move to right subtree
after processing the left subtree on the stack / queue is not required. The
binary trees which store such information in NULL pointers are called
Threaded Binary Trees.
What to store in the null links?
The common convention is put predecessor/successor information. That
means, if TBT to be constructed is an In-order-TBT then for a given node
left pointer will contain in-order predecessor information and right pointer
will contain In-order successor information. These special Pointers are
called Threads.

Types of Threaded Binary Trees:


Based on above forms we get three representations for threaded binary
trees .
1. Pre-order Threaded Binary Trees: NULL left pointer will contain Pre-
order predecessor information and NULL right pointer will contain Pre-
order successor information.
2. In-order Threaded Binary Trees: NULL left pointer will contain In-
order predecessor information and NULL right pointer will contain In-
order successor information.
3. Post-order Threaded Binary Trees: NULL left pointer will contain
Post-order predecessor information and NULL right pointer will contain
Post-order successor information.
In-Order Threaded Binary Tree
Using above concept, if right link of node p (i.e. RCHILD (p) ) is null, then
it can be replaced with a pointer (thread) to a node which would
immediately succeed the node p (i.e. successor of p) while traversing the
binary tree in In-order manner. Similarly, if left link of node p (i.e.
LCHILD(p) ) is null, then it can be replaced with a pointer (thread) to a
node which would immediately precede the node p (i.e. predecessor of
p)while traversing the binary tree in In-order manner.

For example, (Ref. figure below), let us consider a binary tree for the
prefix arithmetic expression +*/A-BCDE
(Note: It is not mandatory that TBT should be constructed only by
using either prefix / postfix expression.)

The tree has n=9 nodes, n-1 (i.e. 8) normal (constructional) pointers
(represented by solid directional lines), and n+1 (i.e. 10) null links. In
TBT, the n+1 null links are replaced by Threads (represented by dotted
lines) (Ref. figure below).
If the above tree is traversed in the In-order manner, then the output
would be
A / B – C * D + E ------------------------- (1)

For example, node D’s left link is replaced with a pointer (Thread) to a
node ‘*’ which is an immediate predecessor of node D (Ref. In-order
Traversal in 1). Node D’s right link is replaced with a pointer (Thread) to a
node ‘+’ which is an immediate successor of node D (Ref. In-order
Traversal in 1).

To distinguish between normal (constructional) pointers and a thread two


extra one bit fields i.e. LBIT and RBIT are required in the node structure.
Each node has five fields namely LBIT, LCHILD, DATA, RCHILD, RBIT
and as shown below

LBIT LCHILD DAT RCHIL RBIT


A D

LBIT: ‘0’ if LCHILD is a thread i.e. pointer to predecessor; ‘1’ if


LCHILD is pointer to root of LEFT binary tree
LCHILD: A pointer (address) to root node of LEFT binary tree or left
thread
DATA: Atom or data item or information at node
RCHILD A pointer (address) to root node of RIGHT binary tree or right
: thread
RBIT: ‘0’ if RCHILD is a thread i.e. pointer to successor; ‘1’ if
RCHILD is pointer to root of RIGHT binary tree

In the above figure node ‘A’ s left pointer and node ‘E’ s right pointer have
been left dangling as node ‘A’ doesn’t have any In-order predecessor and
node ‘E’ doesn’t have any In-order successor (Ref. 1). In order to have no
loose Threads, all dangling pointers are connected to a node called as
Head node in all the TBT’s.

The empty in order threaded tree binary tree will have only one HEAD
node as shown in the following diagram

Representation of the TBT in Computer’s Memory by Using the Node


Structure

The complete memory representation for the tree is as shown below


7. Algorithm 1. Pseudo “C” code for Pre-order traversal
s
/Pseudoco void Pre-order (tbt head)
de { tbt temp;
int flag=1;
temp = head->lchild; //get the address of the root node
cout<< “PREORDER”;
do
{
if(flag==1)
cout<<temp->data; //Display Data (D)
if(temp->lbit && flag==1)
temp=temp->lchild;//Traverse Left (L)
else
{ flag=temp->rbit;
temp=temp->rchild; // Traverse Right (R)
}
} while (temp! =head);
}

2. Pseudo “C” code for In-order traversal

void In-order (tbt head)


{ tbt temp;
int flag=1;
temp = head->lchild; //get the address of the root node
cout<< “INORDER”;
do
{
if(temp->lbit && flag==1)
temp=temp->lchild;//Traverse Left (L)
else
{ cout<<temp->data); //Display Data (D)
flag=temp->rbit;
temp=temp->rchild; // Traverse Right (R)
}
} while (temp! =head);
}
Analysis of Algorithm:

1. Time Complexity:
Time complexity for the construction of binary tree from input prefix
expression is O (n), while loop is executed for time which is equal to
number of nodes in constructed binary tree.

Time complexity for normal binary tree traversal whether recursive or non-
recursive is also O(n), where ‘n’ is equal to number of nodes in binary
tree, since every node is visited only once in both. For the TBT, it is still
O(n), but it is constant times less than recursive and non-recursive using
stack.

2. Space Complexity:
In recursive and non-recursive traversals of normal binary tree. We need
a stack of depth ‘k’ which is equal to height or depth of a binary tree. But
in TBT stack is not required.

8. Test cases Validations :


/ validation Test Cases
Test your program for following cases
For each test cases
a) Display the total number of comparisons required to construct the
in order TBT.
b) For each traversal display total number of comparisons

e.g. for the TBT with 9 nodes


Operations performed Theoretical Practical
value value
1 For construction of In-order TBT. 10 10
2 In-order traversal 10 10
3 Pre-order traversal 10 10

9. Declaratio Data structures to be used are


n of data a) Doubly linked list
structures typedef struct linked_list
{
int lbit;
struct linked _list *lchild;
char data;
struct linked _list *rchild;
int rbit;
} node;

b) For construction of TBT one dimensional array of pointers to store


addresses of nodes i.e. Stack
int top;
node *stack [MAX];

10 Program Printout /Softcopy


.
11 Results Input
. /output 1. Enter the prefix arithmetic expression: +*/A-BCDE
Output
Pre order traversal: +*/A-BCDE
In order traversal: A/B-C*D+E

12 Conclusio 1. Have successfully implemented the assignment to implement In-order


. n TBT and to perform In-order, and Pre-order traversals.
2. Learned TBT makes tree traversals easier by making uses of NULL
pointer to store address of the predecessor or successor nodes. For
traversing / searching no additional data structure (stack) is required.
So TBT is efficient in terms of time and space complexity.
3. The time complexity of traversal in a Threaded Binary Search Tree is
O(n).
4. One of the Application of TBT is in Game tree. Game Trees can be
used in playing of the games such as tic-tac-toe, chess. Etc.

You might also like