You are on page 1of 13

PRAKTIKUM ALGORITMA DAN STRUKTUR DATA

MODUL KE-5
BINARY TREE & BINARY SEARCH TREE (BST)

LABORATORIUM PEMROGRAMAN
PROGRAM STUDI TEKNIK INFORMATIKA
FAKULTAS TEKNIK
UNIVERSITAS MUHAMMADIYAH MALANG
2010

I. TUJUAN
Mahasiswa mampu :
1. Memahami struktur pohon tree sebagai model penyimpanan data.
2. Memahami cara menyimpan dan mengakses elemen dari sebuah struktur pohon biner.
3. Memahami struktur pohon biner dalam versi linked list.
4. Memahami operasi-operasi standar yang terkait dengan pohon biner.

II. ALAT YANG DIGUNAKAN


Peralatan yang digunakan :
1. Perangkat PC yang terinstall Java
2. Editor Java

III. DASAR TEORI

IV.PROSEDUR PELAKSANAAN
Prosedur pelaksanaan praktikum adala sebagai berikut :
1. Mahasiswa menerima tugas yang diberikan oleh dosen/asisten
2. Mahasiswa mengerjakan tugas yang diberikan
3. Asisten/dosen menilai pekerjaan mahasiswa

V. LATIHAN PRAKTIKUM
1. Interface BinaryTree
import java.lang.reflect.*;
public interface BinaryTree
{
public boolean isEmpty();
public Object root();
public void makeTree(Object root, Object left, Object right);
public BinaryTree removeLeftSubtree();
public BinaryTree removeRightSubtree();
public void preOrder(Method visit);
public void inOrder(Method visit);
public void postOrder(Method visit);
public void levelOrder(Method visit);
}

2. Class BinaryTreeNode
public class BinaryTreeNode
{
// package visible data members
Object element;
BinaryTreeNode leftChild; // left subtree
BinaryTreeNode rightChild; // right subtree
// constructors
public BinaryTreeNode() {}
public BinaryTreeNode(Object theElement)
{element = theElement;}
public
BinaryTreeNode(Object
theleftChild,BinaryTreeNode therightChild)
{
element = theElement;
leftChild = theleftChild;
rightChild = therightChild;
}

theElement,BinaryTreeNode

// accessor methods
public BinaryTreeNode getLeftChild() {return leftChild;}
public BinaryTreeNode getRightChild() {return rightChild;}
public Object getElement() {return element;}
// mutator methods
public void setLeftChild(BinaryTreeNode theLeftChild)
{leftChild = theLeftChild;}
public void setRightChild(BinaryTreeNode theRightChild)
{rightChild = theRightChild;}
public void setElement(Object theElement)
{element = theElement;}
// output method
public String toString()
{return element.toString();}
}

3. Class LinkedBinaryTree

import java.lang.reflect.*;
public class LinkedBinaryTree implements BinaryTree
{
// instance data member
BinaryTreeNode root; // root node
// class data members
static Method visit;
// visit method to use during a traversal
static Object [] visitArgs = new Object [1];
// parameters of visit method
static int count;
// counter
static Class [] paramType = {BinaryTreeNode.class};
// type of parameter for visit
static Method theAdd1; // method to increment count by 1
static Method theOutput; // method to output node element
// method to initialize class data members
static
{
try
{
Class lbt = LinkedBinaryTree.class;
theAdd1 = lbt.getMethod("add1", paramType);
theOutput = lbt.getMethod("output", paramType);
}
catch (Exception e) {}
// exception not possible
}
// only default constructor available
// class methods
/** visit method that outputs element */
public static void output(BinaryTreeNode t)
{System.out.print(t.element + " ");}
/** visit method to count nodes */
public static void add1(BinaryTreeNode t)
{count++;}
// instance methods
/** @return true iff tree is empty */
public boolean isEmpty()
{return root == null;}
/** @return root element if tree is not empty
* @return null if tree is empty */
public Object root()
{return (root == null) ? null : root.element;}
/** set this to the tree with the given root and subtrees
* CAUTION: does not clone left and right */
public void makeTree(Object root, Object left, Object right)
{
this.root = new BinaryTreeNode(root,
((LinkedBinaryTree) left).root,
((LinkedBinaryTree) right).root);
}

/** remove the left subtree


* @throws IllegalArgumentException when tree is empty
* @return removed subtree */
public BinaryTree removeLeftSubtree()
{
if (root == null)
throw new IllegalArgumentException("tree is empty");
// detach left subtree and save in leftSubtree
LinkedBinaryTree leftSubtree = new LinkedBinaryTree();
leftSubtree.root = root.leftChild;
root.leftChild = null;
}

return (BinaryTree) leftSubtree;

/** remove the right subtree


* @throws IllegalArgumentException when tree is empty
* @return removed subtree */
public BinaryTree removeRightSubtree()
{
if (root == null)
throw new IllegalArgumentException("tree is empty");
// detach right subtree and save in rightSubtree
LinkedBinaryTree rightSubtree = new LinkedBinaryTree();
rightSubtree.root = root.rightChild;
root.rightChild = null;
}

return (BinaryTree) rightSubtree;

/** preorder traversal */


public void preOrder(Method visit)
{
this.visit = visit;
thePreOrder(root);
}
/** actual preorder traversal method */
static void thePreOrder(BinaryTreeNode t)
{
if (t != null)
{
visitArgs[0] = t;
try {visit.invoke(null, visitArgs);} // visit tree root
catch (Exception e)
{System.out.println(e);}
thePreOrder(t.leftChild);
// do left subtree
thePreOrder(t.rightChild);
// do right subtree
}
}
/** inorder traversal */
public void inOrder(Method visit)
{
this.visit = visit;
theInOrder(root);
}
/** actual inorder traversal method */
static void theInOrder(BinaryTreeNode t)

if (t != null)
{
theInOrder(t.leftChild);
// do left subtree
visitArgs[0] = t;
try {visit.invoke(null, visitArgs);} // visit tree root
catch (Exception e)
{System.out.println(e);}
theInOrder(t.rightChild);
// do right subtree
}

/** postorder traversal */


public void postOrder(Method visit)
{
this.visit = visit;
thePostOrder(root);
}
/** actual postorder traversal method */
static void thePostOrder(BinaryTreeNode t)
{
if (t != null)
{
thePostOrder(t.leftChild);
// do left subtree
thePostOrder(t.rightChild);
// do right subtree
visitArgs[0] = t;
try {visit.invoke(null, visitArgs);} // visit tree root
catch (Exception e)
{System.out.println(e);}
}
}
/** level order traversal */
public void levelOrder(Method visit)
{
ArrayQueue q = new ArrayQueue();
BinaryTreeNode t = root;
while (t != null)
{
visitArgs[0] = t;
try {visit.invoke(null, visitArgs);} // visit tree root
catch (Exception e)
{System.out.println(e);}
// put t's children on queue
if (t.leftChild != null)
q.put(t.leftChild);
if (t.rightChild != null)
q.put(t.rightChild);

// get next node to visit


t = (BinaryTreeNode) q.remove();

}
/** output elements in preorder */
public void preOrderOutput()
{preOrder(theOutput);}
/** output elements in inorder */

public void inOrderOutput()


{inOrder(theOutput);}
/** output elements in postorder */
public void postOrderOutput()
{postOrder(theOutput);}
/** output elements in level order */
public void levelOrderOutput()
{levelOrder(theOutput);}
/** count number of nodes in tree */
public int size()
{
count = 0;
preOrder(theAdd1);
return count;
}
/** test program */
public static void main(String [] args)
{
LinkedBinaryTree a = new LinkedBinaryTree(),
x = new LinkedBinaryTree(),
y = new LinkedBinaryTree(),
z = new LinkedBinaryTree();
y.makeTree(new Integer(1), a, a);
z.makeTree(new Integer(2), a, a);
x.makeTree(new Integer(3), y, z);
y.makeTree(new Integer(4), x, a);
System.out.println("Preorder sequence is ");
y.preOrderOutput();
System.out.println();
System.out.println("Inorder sequence is ");
y.inOrderOutput();
System.out.println();
System.out.println("Postorder sequence is ");
y.postOrderOutput();
System.out.println();
System.out.println("Level order sequence is ");
y.levelOrderOutput();
System.out.println();
System.out.println("Number of nodes = " + y.size());
}

Output LinkedBinaryTree :

4. Class ArrayBinaryTree
public class ArrayBinaryTree
{
// data members
static Object [] a; // array that contains the tree
static int last;
// position of last element in array a
/** visit method that prints the element in a[i] */
public static void visit(int i)
{System.out.print(a[i] + " ");}
/** inorder traversal */
public static void inOrder(Object [] theArray, int theLast)
{
// set static data members
a = theArray;
last = theLast;
// start the recursive traversal method at the root
theInOrder(1);
}
/** actual method to do the inorder traversal */
static void theInOrder(int i)
{// traverse subtree rooted at a[i]
if (i <= last && a[i] != null)
{// root exists
theInOrder(2 * i);
// do left subtree
visit(i);
// visit tree root
theInOrder(2 * i + 1);
// do right subtree
}
}
/** test program */
public static void main(String [] args)
{
Integer [] a = new Integer [15];
a[1] = new Integer(1);
a[2] = new Integer(2);
a[5] = new Integer(5);
a[10] = new Integer(10);
a[11] = new Integer(11);
System.out.println("The elements in inorder are");
inOrder(a, 11);
System.out.println();
}

Output ArrayBinaryTree.java

5. Class BinarySearchTree
import java.util.*;
class Node{
int data;
Node left;
Node right;
Node(int x){
this.data = x;
}
}
public class BinarySearchTree{
private Node root;
/**
* Mengecek apakah tree masih kosong
**/
private boolean isEmpty(){
return (root == null);
}
/**
* Memasukkan suatu nilai ke dalam tree.
* Jika nilai tersebut lebih kecil dari nilai node, maka bergerak ke kiri terus
* hingga menjadi child, begitu juga sebaliknya.
**/
public void insert(int input){
Node temp = new Node(input);
if (isEmpty())
root = temp;
else {
Node cursor = root,
parent = null;
while (cursor != null){
parent = cursor;
if (input < cursor.data)
cursor = cursor.left;
else
cursor = cursor.right;
}
/**
* Menambahkan Node baru pada kiri/kanan Node parent bergantung
* pada nilai input dan nilai yang disimpan Node parent
**/
if (input < parent.data){
parent.left = temp;
return;
}
else {
parent.right = temp;
return;
}
}

}
/* Mencari suatu nilai dalam tree berdasarkan prinsip :
* Selama belum menemukan nilai yang sama,
* Jika nilai yang dicari lebih kecil dari nilai yang disimpan dalam Node
* maka bergerak ke left Child begitu juga sebaliknya.
**/
public boolean delete(int key){
Node cursor = root,
parent = null;
boolean found = false,
isLeftChild = true; //menandai apakah Node yang dihapus merupakan left child
if (!isEmpty()){
while (cursor != null){
parent = cursor;
if (key == cursor.data){
found = true;
break;
}
else if (key < cursor.data){
isLeftChild = true;
cursor = cursor.left;
}
else {
isLeftChild = false;
cursor = cursor.right;
}
}
if (!found)
return false;
else {
/**
* Untuk menghapus leaf (tidak punya child)
**/
if (cursor.left == null && cursor.right == null){
if (cursor == root)
root = null;
else if (isLeftChild)
parent.left = null;
else
parent.right = null;
}
/* Jika node yang akan dihapus hanya memiliki salah satu subtree
* maka tinggal memindahkan subtree menggantikan node yang dihapus
**/
else if (cursor.left == null){
if (cursor == root)
root = cursor.right;
else if (isLeftChild)
parent.left = cursor.right;
else
parent.right = cursor.right;
}
else if (cursor.right == null){
if (cursor == root)
root = cursor.left;
else if (isLeftChild)
parent.left = cursor.left;
else
parent.right = cursor.left;
}

/**
* Jika node yang akan dihapus memiliki 2 child, maka cari successornya
* dengan fungsi getSuccessor kemudian hubungkan subtree bagian kanan
* dari node yang dihapus dengan successor
**/
else {
Node successor = getSuccessor(cursor);
if (cursor == root)
root = successor;
else if (isLeftChild)
parent.left = successor;
else
parent.right = successor;
//menyambung successor dengan cursor.right
successor.right = cursor.right;
}
}
}
return true;
}
private Node getSuccessor(Node localNode){
Node parent = null,
successor = localNode,
cursor = localNode.left;
while (cursor != null){
parent = successor;
successor = cursor;
cursor = cursor.right;
}
if (successor != localNode.left){
parent.right = successor.left;
successor.left = localNode.left;
}
return successor;
}
/**
* Method traverse untuk mengelilingi Node-Node dalam tree
**/
public void traverse(int tipe){
switch (tipe){
case 1:
System.out.print("\nPreorder traversal:\n");
preOrder(root);
break;
case 2:
System.out.print("\nInorder traversal:\n");
inOrder(root);
break;
case 3:
System.out.print("\nPostorder traversal:\n");
postOrder(root);
break;
}
System.out.println('\n');
}
private void preOrder(Node localRoot){
if (localRoot == null) return;
System.out.print(localRoot.data+" ");
preOrder(localRoot.left);
preOrder(localRoot.right);
}

private void inOrder(Node localRoot){


if (localRoot == null) return;
inOrder(localRoot.left);
System.out.print(localRoot.data+" ");
inOrder(localRoot.right);
}
private void postOrder(Node localRoot){
if (localRoot == null) return;
postOrder(localRoot.left);
postOrder(localRoot.right);
System.out.print(localRoot.data+" ");
}

public static void main(String[] args)


{
BinarySearchTree a = new BinarySearchTree();
//penambahan node pada binary tree
a.insert(5);
a.insert(4);
a.insert(6);
a.insert(1);
a.insert(4);
a.insert(9);
//penelusuran node pada binary tree
a.traverse(1); //pre-order
a.traverse(2); //in-order
a.traverse(3); //post-order
}

output class BinarySearchTree :

VI. TUGAS PRAKTIKUM


1. Modifikasi Program LinkedBinaryTree.java dengan menambahkan method untuk
mendapatkan height/tinggi dari sebuah binary tree.
public class LinkedBinaryTree implements BinaryTree
{
........................
//tambahkan method theHeight pada class LinkedBinaryTree.java
static int theHeight(BinaryTreeNode t)
{
//tulis kode disini untuk mendapatkan tinggi binary tree
}
.............................
}

Tampilkan hasil pemanggilan method theHeight pada main method.

2. Dengan menggunakan class LinkedBinaryTree buatlah tree dengan struktur hirarki


seperti gambar 1.

Gambar 1
3. Dengan menggunakan class ArrayBinaryTree buatlah tree dengan struktur hirarki seperti
gambar 1.
4. Modifikasi class ArrayBinaryTree dengan menambahkan method preOrder dan
postOrder. Petunjuk : modifikasi method theInOrder.
static void theInOrder(int i)
{
// traverse subtree rooted at a[i]
if (i <= last && a[i] != null)
{// root exists
theInOrder(2 * i);
// do left subtree
visit(i);
// visit tree root
theInOrder(2 * i + 1);
// do right subtree
}
}

Tampilkan hasil dari pemanggilan method preOrder dan postOrder pada main method.
5. Dengan menggunakan class BinarySearchTree lakukan pemanggilan method insert()
dengan mengirimkan input berturut-turut sesuai dengan deret berikut : {10,
5,20,2,6,19,25,21}, root adalah 10.
Gambarkan hasil akhir binary search tree tersebut!

VII. HASIL PRAKTIKUM


[Tuliskan hasil tugas praktikum di sini]

You might also like