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

LBYCPA2 Laboratory Manual - Module 5

Manual

Uploaded by

bubbakesh15
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)
26 views15 pages

LBYCPA2 Laboratory Manual - Module 5

Manual

Uploaded by

bubbakesh15
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/ 15

LBYCPA2 - Data Structures and Algorithms Laboratory

AY 2023-24, Term 1

Module 5: Tree Data Structures

Objectives:
1. To create a program using a tree data structure.
2. To be able to know how to use a pre, in, and post-order traversal.
3. To determine the process of a tree traversal using recursion.
4. To utilize a custom tree data structure in an actual application
5. (Student #TODO: Add custom/more objectives in final *report*)

Discussion:

A tree is a collection of nodes. The collection can be empty. If not empty, a tree consists of a
distinguished node R (the root), and zero or more nonempty subtrees T1, T2, ...., Tk, each of
whose roots are connected by a directed edge from R.

Figure 1. Generic Tree

Tree Terminologies

Root - It is the mother node of a tree structure. This tree does not have a parent. It is the
first node in hierarchical arrangement.

61
Node - The node of a tree stores the data and its role is the same as in the linked list.
Nodes are connected by the means of links with other nodes.

Parent - It is the immediate predecessor of a node. In figure 2, A is the parent of B and C.

Figure 2. Parent and Child Illustration

Child - When a predecessor of a node is a parent then all successor nodes are called child
nodes. In figure 2, B and C are the child nodes of A.

Link / Edge - An edge connects the two nodes. The line drawn from one node to another
node is called edge / link. Link is nothing but a pointer to a node in a tree structure.

Leaf - This node is located at the end of the tree. It does not have any child hence it is called
a leaf node.

Level - Level is the rank of the tree hierarchy. The whole tree structure is leveled. The level
of the root node is always at 0. The immediate children of the root are at level 1 and their
children are at level 2, and so on.

Height - The highest number of nodes that is possible in a way starting from the first node
(root) to a leaf node is called the height of the tree as shown in Figure 3.

The formula for finding the height of a tree is h = imax + 1, where h is the height and i is the
max.

62
Figure 3. Height Illustration

Sibling - The child nodes of the same parent are called siblings. They are also called brother
nodes.

Degree of a Node - The maximum number of children that exists for a node is called the
degree of a node.

Terminal Node - The node with degree zero is called a terminal node or leaf.

Path length - Is the number of successive edges from the source node to the destination
node.

Ancestor and descendant - Proper ancestor and proper descendant.

Depth - The depth of a binary tree is the maximum level of any leaf of a tree.

Forest - It is a group of disjoint trees. If we remove a root node from a tree, then it becomes
a forest.

Binary Tree

The simplest form of tree is a binary tree. A binary tree consists of a node (called the root
node) and left and right subtrees. Both the sub-trees are themselves binary trees.

Also, a tree is binary if each node of it has a maximum of two branches i.e. a node of a
binary tree can have a maximum of two children.

A complete binary tree is a tree in which each level of the tree is completely filled. Except,
possibly the bottom level.

63
Figure 4. Linked Implementation of Tree

The fundamental component of a binary tree is the node. A binary tree node should consist
of three things.

Data - Stores given values

Left child - is a link field and hold the address of its left node

Right child - is a link field and holds the address of its right node.

Operations on Binary Tree

Create - Create an empty binary tree

Empty - Return true when the binary tree is empty else return false.

Lchild - A pointer is returned to the left child of a node, when a node is without a left child,
a NULL pointer is returned.

Rchild - A pointer is returned to the right child of a node, when a node is without a left
child, a NULL pointer is returned.

64
Father/Parent - A pointer to the father of a node is returned.

Sibling - A pointer to the brother of the node is returned or else a NULL pointer is returned.

Tree Traversal - Inorder Traversal, Preorder Traversal, Postorder Traversal

Insert - To insert a node

Deletion - To delete a node

Search - To search a given node

Copy - Copy one tree into another.

Example

Leaves are operands (constants or variables)

The other nodes (internal nodes) contain operators

Used to display/access the data in a tree in a certain order.

In traversing, the right subtree is traversed after the left sub-tree.

Three methods of traversing:

65
Preorder Traversing: Root – Left –Right

Inorder Traversing: Left – Root – Right

Postorder Traversing: Left – Right – Root

Answer:
Preorder traversal Inorder traversal Postorder Traversal
node – left – right left, node, right left, right, node
Prefix expression Infix expression Postfix expression
++a*bc*+*defg a+b*c+d*e+f*g abc*+de*f+g*+

Binary Search Tree

Stores keys in the nodes in a way so that searching, insertion, and deletion can be done
efficiently.

The binary search tree is either empty or each node N of tree satisfies the following
property

The key value in the left child is not more than the value of the root node.

The key value in the right child is more than or identical to the value of the root node.

All the sub-trees, i.e. left and right subtrees follow the two rules mentioned above.

Searching in Binary Search Tree

Three steps of searching

1. The item which is to be searched is compared with the root node. If the item is equal to
the root, then we are done.
2. If it’s less than the root node then we search in the left sub-tree.
3. If it's more than the root node then we search in the right sub-tree.

The above process will continue until the item is found or you reached the end of the tree.

Example:

66
Given the figure below search for 9

Solution:

1. Compare 9: 15 (root), go to left sub-tree;


2. Compare 9: 6, go to right subtree;
3. Compare 9: 7, go to right subtree;
4. Compare 9: 13, go to left sub-tree;
5. Compare 9: 9, searching successful

Insertion in Binary Search Tree

Three steps of insertion

1. If the root of the tree is NULL then insert the first node and root points to that node.
2. If the inserted number is lesser than the root node then insert the node in the left
subtree.
3. If the inserted number is greater than the root node then insert the node in the right
subtree.

Deletion in Binary Search Tree

67
When we delete a node, we need to consider how we take care of the children of the
deleted node.

This must be done such that the property of the search tree is maintained.

Three cases:

1. The node is a leaf. Delete it immediately.


2. The node has one child. Adjust a pointer from the parent to bypass that node.
3. The node has 2 children. Replace the key of that node with the minimum element in
the right subtree. Delete the minimum element. Has either no child or only right child
because if it has a left child, that left child would be smaller and would have been
chosen.

Heaps

Heap is a special Tree-based structure in which the tree is a complete binary tree. The
operations on the heap data structure are: Heapify, Insertion, Deletion, and Peek.
There are two types: the Min-heap and the Max-heap tree.

Min-Heap - the key present at the root node MUST be the MINIMUM among the keys
present among all children. This property must be true recursively to all the subtrees in the
heap.

Max-Heap - the key present at the root node MUST be the MAXIMUM among the keys
present among all children. This property must be true recursively to all subtrees in the
heap.

AVL Tree

The AVL tree is a self-balancing BST in which each node contains information about the
Balancing factor, whose value is either -1, 0, or 1. The operations in an AVL tree are
Insertion, Deletion, and Searching algorithms.

68
The property of an AVL tree is the balancing of the data in the tree. The balancing is done
by rotation.

Laboratory Familiarization Exercises

Direction: Encode the following program and compile. Simulate each line of the program.
Demonstrate the corresponding output for each of the given programs. Give your
observation and analysis

Program No. 1

public class TreeAct {

class TreeNode {
TreeNode left;
TreeNode right;
int data;

TreeNode(){
left = null;
right = null;
}

TreeNode(int data) {
left = null;
right = null;
this.data = data;
}
}

TreeNode root;

public TreeAct () {
root = null;
}

boolean isEmpty() {
return root == null;
}

void insert (int d) {

69
root = insertRec(root, d);
}

TreeNode insertRec (TreeNode root, int d) {


if (root == null) {
root = new TreeNode(d);
return root;
}

//else traverse down the list


else if (d < root.data) {
root.left = insertRec(root.left, d);
} else if (d > root.data) {
root.right = insertRec(root.right, d);
}
return root;
}

void remove (int d) {


root = deleteRec(root, d);
}

TreeNode deleteRec(TreeNode root, int d) {


if (root == null) {
System.out.println("Tree is empty or data not found");
return root;
}

if (d < root.data) {
root.left = deleteRec(root.left, d);
} else if (d > root.data) {
root.right = deleteRec(root.right, d);
}
// If the data is the same as the node, then delete
else if (d == root.data) {
if (root.left == null) {
return root.right;
} else if (root.right == null) {
return root.left;
}

root.data = minValue(root.right);
root.right = deleteRec(root.right, root.data);
} else {
System.out.println("Data not found");
}
return root;
}

70
int minValue (TreeNode root) {
int minv = root.data;
while (root.left != null){
minv = root.left.data;
root = root.left;
}
return minv;
}

void inorder(){
inorderRec(root);
}
void inorderRec(TreeNode root) {
if (root != null) {
inorderRec(root.left);
System.out.println(root.data + " ");
inorderRec(root.right);
}
}

void preorder() {
preorderRec(root);
}
void preorderRec(TreeNode root) {
if (root != null) {
/* first print data of node */
System.out.println(root.data + " ");
/* then recur on left subtree */
preorderRec(root.left);
/* now recur on right subtree */
preorderRec(root.right);
}
}

void postorder() {
postorderRec(root);
}
void postorderRec(TreeNode root) {
if (root != null) {
/* then recur on left subtree */
postorderRec(root.left);
/* now recur on right subtree */
postorderRec(root.right);
/* first print data of node */
System.out.println(root.data + " ");
}
}

71
public static void main(String[] args){
TreeAct tree = new TreeAct();
/* Let us create following BST
50
/ \
30 70
/ \ / \
20 40 60 80 */

tree.insert(50);
tree.insert(30);
tree.insert(20);
tree.insert(40);
tree.insert(70);
tree.insert(60);
tree.insert(80);
System.out.println(
"Inorder traversal of the given tree");
tree.inorder();

System.out.println("Preorder traversal");
tree.preorder();

System.out.println("Postorder traversal");
tree.postorder();

System.out.println("\nDelete 10");
tree.remove(10);
System.out.println(
"Inorder traversal of the modified tree");
tree.inorder();

System.out.println("\nDelete 30");
tree.remove(30);
System.out.println(
"Inorder traversal of the modified tree");
tree.inorder();

System.out.println("\nDelete 50");
tree.remove(50);
System.out.println(
"Inorder traversal of the modified tree");
tree.inorder();
}
}

72
Laboratory Problems/Activities

1. Make a Java program using tree that has the capability to display the in-order,
pre-order, and post-order of this equation: (((A + B) * (N - I)) / (M* E)). Provide the
following:
a) algorithm pseudocode (Final Report)
b) flowchart, (Final Report) (Optional)
c) source code, (Canvas Submission and Final Report)
d) observation, and (Final Report)
e) screenshot of the output (Canvas Submission and Final Report)

2. Implement a binary search tree (BST) structure in Java. Using alphabetical order,
construct a binary search tree for the words in the sentence “The quick brown fox
jumps over the lazy dog.” Provide the following:
a) algorithm pseudocode (Final Report)
b) source code, (Canvas Submission and Final Report)
c) JUnit test, (Canvas Submission and Final Report)
d) observation, and (Final Report)
e) screenshot of the output (Canvas Submission and Final Report)

3. Implement the Heapify algorithm in Java from inputting a BST. Create a Min-heapify
and a Max-heapify function where the input is the BST structure that contains “The
quick brown fox jumps over the lazy dog.”. Provide the following:
a. algorithm pseudocode (Final Report)
b. source code, (Canvas Submission and Final Report)
c. JUnit test, (Canvas Submission and Final Report)
d. observation, (Final Report)

4. Implement an AVL tree. Since the property of an AVL tree has a self-balancing
algorithm, it avoids the data being skewed. The BST of “The quick brown fox jumps
over the lazy dog.” is a skewed BST. Hence, when it is placed in an AVL tree, it should
balance out. Input the same sentence on an AVL tree. Provide the following outputs:
a. algorithm pseudocode (Final Report)
b. source code, (Canvas Submission and Final Report)

73
c. JUnit test of the insert, deletion, left and right rotation functions. (Canvas
Submission and Final Report)
d. observation, (Final Report)

5) Research about Minimax tree search algorithm which is popular in creating game AI for
simple games, i.e. Checkerboard and Chess. Write your own custom tree to create a
Minimax Tree for a Tic-Tac-Toe game. Develop an application for Human vs. Minimax AI
Tic-Tac-Toe game. Provide the following:
a) Minimax algorithm pseudocode (Final Report)
b) source code, (Canvas Submission and Final Report)
c) observation, and (Final Report)
d) video capture of the output (Canvas Submission and Final Report)

Additional Information:

The game tree for tic-tac-toe is extremely large and cannot be drawn here, although a
computer could easily build such a tree. We show a portion of the game tree for tic-tac-toe
in the Figure below. Note that by considering symmetric positions equivalent, we need only
consider three possible initial moves. We also show a subtree of this game tree leading to
terminal positions, where a player who can win makes a winning move.

74
We can recursively define the values of all vertices in a game tree in a way that enables us
to determine the outcome of this game when both players follow optimal strategies. By a
strategy we mean a set of rules that tells a player how to select moves to win the game. An
optimal strategy for the first player is a strategy that maximizes the payoff to this player
and the second player is a strategy that minimizes this payoff. We now recursively define
the value of a vertex.
The value of a vertex in a game tree is defined recursively as:
(a) the value of a leaf is the payoff to the first player when the game terminates in the
position represented by this leaf.
(b) the value of an internal vertex at an even level is the maximum of the values of its
children, and the value of an internal vertex at an odd level is the minimum of the values of
its children.
The strategy where the first player moves to a position represented by a child with
maximum value and the second player moves to a position of a child with minimum value
is called the minimax strategy. We can determine who will win the game when both players
follow the minimax strategy by calculating the value of the root of the tree; this value is
called the value of the tree.

75

You might also like