You are on page 1of 14

KING ABDULAZIZ UNIVERSITY

Faculty of Computing & Information Technology


Department of Computer Science

Lab Manual

CPCS204
Data Structures 1
1433/1434H

Lab - 7

Learning Procedure

1) Stage J (Journey inside-out the concept)


2) Stage a1 (apply the learned)
3) Stage v (verify the accuracy)
4) Stage a2 (assess your work)
Term I
2013 Lab-7: Trees

Laboratory 7:

Statement Purpose:
This lab will give you practice with Trees.

Activity Outcomes:
This lab teaches you the following topics:

• Simple Binary Ordered Tree class


• Implementation of 4 different traversals of binary trees
• Recalling recursion by implementing various binary tree methods
• Recursive implementation of binary search tree
• Learn and understand the characteristics of Binary Trees

Instructor Note:
As pre-lab activity, review Ch10 and Ch11, from the book Data Structures with
Java by John R. Hubbard and also the relevant instructor’s slides.

Names I.D.

1. .……………..………………………………. ………………………………

2. ..…………………………………………….. ………………………………

3. .……………………………………………... ………………………………

4. .…………………………………………….. ..…………………………….

CPCS204 – The Lab Note Lab-7 1


Term I
2013 Lab-7: Trees

1) Stage J (Journey)
Trees: tree is a nonlinear data structure that models a hierarchical
organization. The characteristic features are that each element may have
several successors (called its “children”) and every element except one (called
the “root”) has a unique predecessor (called its “parent”).

(Nick P., 2001) A Bnary Tree: is made of nodes, where each node contains a
"left" pointer, a "right" pointer, and a data element. The "root" pointer points
to the topmost node in the tree. The left and right pointers recursively point to
smaller "subtrees" on either side. A null pointer represents a binary tree with
no elements -- the empty tree.

The formal recursive definition is: a binary tree is either empty (represented by
a null pointer), or is made of a single node, where the left and right pointers
(recursive definition ahead) each point to a binary tree.

Simple example:

A "binary search tree" (BST) or "ordered binary tree" is a type of binary tree
where the nodes are arranged in order: for each node, all elements in its left
subtree are less-or-equal to the node (<=), and all the elements in its right
subtree are greater than the node (>). The tree shown above is a binary search
tree -- the "root" node is a 5, and its left subtree nodes (1, 3, 4) are <= 5, and
its right subtree nodes (6, 9) are > 5. Recursively, each of the subtrees must
also obey the binary search tree constraint: in the (1, 3, 4) subtree, the 3 is the
root, the 1 <= 3 and 4 > 3. Watch out for the exact wording in the problems -- a
"binary search tree" is different from a "binary tree".

CPCS204 – The Lab Note Lab-7 2


Term I
2013 Lab-7: Trees

The nodes at the bottom edge of the tree have empty subtrees and are called
"leaf" nodes (1, 4, 6) while the others are "internal" nodes (3, 5, 9).

Programing Strategy:

When thinking about a binary tree problem, it's often a good idea to draw a
few little trees to think about the various cases. For any problem related to
binary trees, there are two things to understand.

▪ The node/pointer structure that makes up the tree and the code that
manipulates it
▪ The algorithm, typically recursive, that iterates over the tree

Criteria of Binary Trees:

1. Binary trees have several interesting properties dealing with


relationships between their heights and number of nodes.
2. We denote the set of all nodes of a tree T at the same depth d as the
level d of T.
3. In a binary tree, level 0 has at most one node (the root), level 1 has at
most two nodes (the children of the root), level 2 has at most four
nodes, and so on.
4. We can see that the maximum number of nodes on the levels of a binary
tree grows exponentially as we go down the tree.

CPCS204 – The Lab Note Lab-7 3


Term I
2013 Lab-7: Trees

Traversals of Binary Trees:

Depth-first

1. Preorder traversal sequence: F, B, A, D, C, E, G, I, H (root, left, right)


2. Inorder traversal sequence: A, B, C, D, E, F, G, H, I (left, root, right); note
how this produces a sorted sequence
3. Postorder traversal sequence: A, C, E, D, B, H, I, G, F (left, right, root)

Breadth-first

4. Level-order traversal sequence: F, B, G, A, D, I, C, E, H

CPCS204 – The Lab Note Lab-7 4


Term I
2013 Lab-7: Trees

2) Stage a1 (apply)
Activity1:
Java Ordered Binary Tree Structure

Task 1: Create a new java project and add the BinaryTree.java and
TestBinaryTree.java below then complete the following tasks.

Task 2: based on the code of TestBinaryTree.java, draw the created


binary tree that shows the entered values.
// Testing the Binary Tree Class
public class TestBinaryTree {

public static void main(String[] args) {

BinaryTree T = new BinaryTree();


T.insert(5);
T.insert(3);
T.insert(9);
T.insert(1);
T.insert(4);
T.insert(6);
System.out.println("The root of Bi-Tree is:
"+T.root().data);
System.out.println("In-order traversal sequence :");
T.inOrder();
System.out.println("Pre-order traversal sequence :");
T.preOrder();
System.out.println("Post-order traversal sequence
:");
T.postOrder();
System.out.println("Level-order traversal sequence
:");
T.levelOrder();
//Write searching here of Task 10
T.mirror();

System.out.println("In-order traversal sequence


(after mirroring) :");
T.inOrder();
}
}
// Example: Ordered Binary Tree structure
import java.util.*;

CPCS204 – The Lab Note Lab-7 5


Term I
2013 Lab-7: Trees

// BinaryTree.java
public class BinaryTree {
// Root node pointer. Will be null for an empty tree.

private Node root;

/*
--Node--
The binary tree is built using this nested node class.
Each node stores one data element, and has left and right
sub-tree pointer which may be null.
The node is a "dumb" nested class -- we just use it for
storage; it does not have any methods.
*/
public static class Node {

Node left;
Node right;
int data;

Node(int newData) {
left = null;
right = null;
data = newData;
}
}

/**
Creates an empty binary tree -- a null root pointer.
*/
public BinaryTree() {
root = null;
}

/**
Inserts the given data into the binary tree.
Uses a recursive helper.
*/
public void insert(int data) {
root = insert(root, data);
}

/**
Recursive insert -- given a node pointer, recur down and
insert the given data into the tree. Returns the new
node pointer (the standard way to communicate
a changed pointer back to the caller).
*/
private Node insert(Node node, int data) {
if (node == null) {
node = new Node(data);
} else {
CPCS204 – The Lab Note Lab-7 6
Term I
2013 Lab-7: Trees

if (data <= node.data) {


node.left = insert(node.left, data);
} else {
node.right = insert(node.right, data);
}
}

return (node); // in any case, return the new pointer


to the caller
}

/**
Returns the number of nodes in the tree.
Uses a recursive helper that recurs
down the tree and counts the nodes.
*/
public int size() {
return (size(root));
}

private int size(Node node) {

//Complete the code here

/**
Returns true if the given target is in the binary tree.
Uses a recursive helper.
*/
public boolean lookup(int data) {
return (lookup(root, data));
}

/**
Recursive lookup -- given a node, recur
down searching for the given data.
*/
private boolean lookup(Node node, int data) {
if (node == null) {
return (false);
}

if (data == node.data) {
return (true);
} else if (data < node.data) {
return (lookup(node.left, data));
} else {
return (lookup(node.right, data));
}
}
CPCS204 – The Lab Note Lab-7 7
Term I
2013 Lab-7: Trees

/**
Prints the node values in the "inOrder" order.
Uses a recursive helper to do the traversal.
*/
public void inOrder() {
inorderTree(root);
System.out.println();
}

private void inorderTree(Node node) {


if (node == null) {
return;
}

// left, node itself, right


inorderTree(node.left);
System.out.print(node.data + " ");
inorderTree(node.right);
}

/**
Prints the node values in the "preOrder" order.
Uses a recursive helper to do the traversal.
*/
public void preOrder() {
preOrder(root);
System.out.println();
}

public void preOrder(Node node) {

//Complete the code here

/**
Prints the node values in the "postOrder" order.
Uses a recursive helper to do the traversal.
*/
public void postOrder() {
postOrder(root);
System.out.println();
}

public void postOrder(Node node) {

//Complete the code here

}
CPCS204 – The Lab Note Lab-7 8
Term I
2013 Lab-7: Trees

/**
Prints the node values in the "levelOrder" order.
Uses a helper to do the traversal.
*/
public void levelOrder() {
levelOrder(root);
System.out.println();
}

public void levelOrder(Node node) {

if (node != null) {

Queue<Node> q = new ArrayDeque<Node>();


q.add(node);

while (q.size() != 0) {

Node currentNode = q.remove();


System.out.print(currentNode.data + " ");

if (currentNode.left != null) {
q.add(currentNode.left);
}

if (currentNode.right != null) {
q.add(currentNode.right);
}
}
}
}

/**
Changes the tree into its mirror image.
Uses a recursive helper that recurs over the tree,
swapping the left/right pointers.
*/
public void mirror() {

//write the code here

private void mirror(Node node) {

//write the code here

public void deleteNode(int x) {


CPCS204 – The Lab Note Lab-7 9
Term I
2013 Lab-7: Trees

deleteNode(x, root);
}

private Node deleteNode(int x, Node n) {


if (n != null) {
if (x < n.data) {
n.left=deleteNode(x, n.left);
}
else if (x > n.data) {
n.right=deleteNode(x, n.right);
}
else if (n.left != null & n.right != null) {
System.out.println("Deleted: "+ n.data);
// Node min = n.right;
// while (min.left != null) {
// min = min.left;
// }
// n.data = min.data;

n.data = findMin(n.right).data;
n.right= removeMinRight(n.right);
}
else{
//Alternative code line
System.out.println("Deleted: "+ n.data);
n = (n.left != null) ? n.left : n.right;
// if(n.left != null)
// n = n.left;
// else
// n = n.right;
}

}
return n;
}

public Node removeMinRight(Node min) {


if (min.left != null) {
min.left=removeMinRight(min.left);
return min;
} else {
return min.right;
}
}

protected Node findMin( Node min ) {


if( min != null )
while( min.left != null )
min = min.left;

return min;
}
CPCS204 – The Lab Note Lab-7 10
Term I
2013 Lab-7: Trees

// public void deleteNodeWay2(int x) {


// //complete the code here
// }
//
// private Node deleteNodeWay2(int x, Node n) {
// //complete the code here
// }
//
// public Node removeMaxLeft(Node max) {
// //complete the code here
// }
//
// private Node findMax( Node max ) {
// //complete the code here
// }

Task 3: Write the code of a constructor public BinaryTree(int data)


that creates a new binary tree and assigns the given data to the root data.

Task 4: Write the code of a method public boolean isEmpty() that Tests
whether the tree has any nodes or not.

Task 5: Write the code of a method public Node root() that returns the
tree's root; an error occurs if the tree is empty.

Task 6: Complete the code of a recursive helper method public int


size() that counts then returns the number of nodes.

Task 7: Complete the code of a recursive helper method public void


preOrder(Node node) to print the node values in the "preOrder" order
Uses a recursive helper to do the traversal such that.
Simple Algorithm:
preorder(node)
if node = null then return
print node.value
preorder(node.left)
preorder(node.right)

Write the expected order of the output:

CPCS204 – The Lab Note Lab-7 11


Term I
2013 Lab-7: Trees

Task 8: Complete the code of a recursive helper method public void


postOrder() to print the node values in the "postOrder" order Uses a
recursive helper to do the traversal.

Simple Algorithm:
postorder(node)
if node = null then return
postorder(node.left)
postorder(node.right)
print node.value

Write the expected order of the output:

3) Stage v (verify)
Task 9: Add two lines of code to the main class TestBinaryTree.java to
search for the values 4 and 8 using the lookup(int data) method.
Task 10: Write the code of a method publicvoid mirror() that Uses a
recursive helper private void mirror(Node node) that recurs over the
tree, swapping the left/right pointers. In which it changes the tree into its
mirror image.
So the tree... is changed to...
4 4
/\ /\
2 5 5 2
/\ /\
1 3 3 1

The final output should be as follows:


Pre-order traversal sequence :
5 3 1 4 9 6
Post-order traversal sequence :
1 4 3 6 9 5
Level-order traversal sequence :
5 3 9 1 4 6
The result of search for (4) is :true
The result of search for (8) is :false
In-order traversal sequence (after mirroring) :
9 6 5 4 3 1

Task 11: Add a testing code to the main class TestBinaryTree.java to in


order to test deleting any or some of the nodes using the method
deleteNodeWay2(int x) and reprint the tree in level-order to see the
difference after the deletion.
CPCS204 – The Lab Note Lab-7 12
Term I
2013 Lab-7: Trees

Task 12: The given deleting method public void deleteNode(int x,


Node node) is replacing a deleted node with 2 children with the successor of
its right sub-tree (i.e. the min node in the right sub-tree).

So now, try to complete the 4 uncompleted methods:


1. public void deleteNodeWay2(int x)
2. private Node deleteNodeWay2(int x, Node n)
3. public Node removeMaxLeft(Node max)
4. private Node findMax( Node max )

In order to perform binary tree node deletion based on replacing a deleted


node with 2 children with the predecessor of its left sub-tree (i.e. the max
node in the left sub-tree).

Task 13: Add testing code to the main class TestBinaryTree.java in order
to check out your new deleting method deleteNodeWay2(int x) and
reprint the tree in level-order to see the difference after the deletion.

4) Stage a2 (assess)
Lab Work:
In each laboratory you are assessed on your work within lab session based on
your participation, discussions and achievement of lab activities. Thus, each lab
has a portion of the (LAB WORK MARK). Therefore, a checklist of each lab is
used to evaluate your work. This checklist accounts the following criteria:

• Following the lab manual step by step


• Answering given questions concisely and precisely
• Practicing and implementing given examples correctly
• Writing code of required programming tasks
• Being focused, positive, interactive and serious during lab session
• Asking good questions or answering instructor questions if any

Note: performing given home activities or extra programming is highly


recommended to improve your understanding, capability and programming
skills.

CPCS204 – The Lab Note Lab-7 13

You might also like