Professional Documents
Culture Documents
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.
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);
}
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
}
}
/** output elements in preorder */
public void preOrderOutput()
{preOrder(theOutput);}
/** output elements in inorder */
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);
}
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!