Asd Modul 4 (Binary)
Asd Modul 4 (Binary)
MODUL KE-4
BINARY TREE & BINARY SEARCH TREE (BST)
LABORATORIUM PEMROGRAMAN
PROGRAM STUDI TEKNIK INFORMATIKA
FAKULTAS TEKNIK
UNIVERSITAS MUHAMMADIYAH MALANG
2015
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.
Tree adalah kumpulan element yang saling terhubung secara hirarki (one to many). Tree
terdiri dari root (akar), path (cabang), dan leaf (daun). Element pada tree yaitu berupa
node. Sebuah node hanya boleh memiliki satu induk/parent. Kecuali root, tidak memiliki
induk/parent. Setiap node dapat memiliki nol atau banyak cabang anak (one to many).
Node yang tidak memiliki cabang anak disebut daun.
Root (Node Root) adalah node yang memiliki hirarki tertinggi, yang pertama kali
dibentuk sehingga tidak memiliki parent (node induk). Penelusuran path tiap node
dimulai dari root. Subtree adalah node-node lain dibawah root yang saling terhubung
satu sama lain secara hirarki.
Path merupakan percabangan dari satu node ke node lainnya. Setiap node dapat
memiliki lebih dari satu cabang node atau tidak sama sekali memiliki cabang.
Leaf adalah node pada tree yang terletak pada pangkal dan tidak memiliki cabang ke
element node lainnya. Dalam artian leaf terdapat pada hirarki terbawah pada sebuah tree.
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
Dokumen Laboratorium Teknik Informatika UMM @ 2015 Modul Praktikum Algoritma
{
theInOrder(t.leftChild);
visitArgs[0] = t;
try {visit.invoke(null, visitArgs);}
catch (Exception e)
{System.out.println(e);}
theInOrder(t.rightChild);
// do left subtree
// visit tree root
// 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);
thePostOrder(t.rightChild);
visitArgs[0] = t;
try {visit.invoke(null, visitArgs);}
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);}
catch (Exception e)
{System.out.println(e);}
// do left subtree
// do right subtree
// visit tree root
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
static void theInOrder(int i)
{// traverse subtree rooted at a[i]
if (i <= last && a[i] != null)
{// root exists
theInOrder(2 * i);
//
visit(i);
//
theInOrder(2 * i + 1);
//
}
}
traversal */
do left subtree
visit tree root
do right subtree
Output ArrayBinaryTree.java
5. Class BinarySearchTree
/** binary search tree */
//package dataStructures;
public class BinarySearchTree extends LinkedBinaryTree
{
// top-level nested class
static class Data
{
// data members
Object element;
// element in node
Comparable key;
// its key
// constructor
Data(Comparable theKey, Object theElement)
{
key = theKey;
element = theElement;
}
public String toString()
{return element.toString();}
}
/** @return element with specified key
* @return null if no matching element */
public Object get(Object theKey)
{
// pointer p starts at the root and moves through
// the tree looking for an element with key theKey
BinaryTreeNode p = root;
Comparable searchKey = (Comparable) theKey;
while (p != null)
// examine p.element.key
if (searchKey.compareTo(((Data) p.element).key) < 0)
p = p.leftChild;
else
if (searchKey.compareTo(((Data) p.element).key) > 0)
p = p.rightChild;
else // found matching element
return ((Data) p.element).element;
// no matching element
return null;
}
/** insert an element with the specified key
* overwrite old element if there is already an
* element with the given key
* @return old element (if any) with key theKey */
public Object put(Object theKey, Object theElement)
{
BinaryTreeNode p = root;
// search pointer
BinaryTreeNode
pp = null;
// parent of p
Comparable elementKey = (Comparable) theKey;
// find place to insert theElement
while (p != null)
{// examine p.element.key
pp = p;
// move p to a child
Dokumen Laboratorium Teknik Informatika UMM @ 2015 Modul Praktikum Algoritma
+
" with key 6");
System.out.println("Elements in ascending order are");
y.ascend();
System.out.println();
// try to remove a nonexistent element
System.out.println("Removed element " + y.remove(new Integer(6))
+
" with key 6");
System.out.println("Elements in ascending order are");
y.ascend();
System.out.println();
}
}
Berikut adalah gambaran bentuk tree dan gambaran hasil running program :
Sitisoni
Nina
Agus
Meri
peni
Toni
Joko
Sinta
Budi
rina
wenda
niko
lori
dina
Keterangan :
1. Tugas praktikum dikerjakan sendiri, jika ketahuan mengcopas, mencontoh, mereplika,
menjiplak dll akan dikenakan sanksi nilai x .
2. Tidak ada demo susulan, sesuai dengan jadwal yang telah ditentukan, kecuali ada alasan
yang logis dan dapat di maklumi.
3. Kriteria penilaian praktikum:
a. 25% Absensi.
b. 50% demo tugas.
c. 25% laporan praktikum.
d. Tambahan nilai (sesuai kebijakan aslab masing-masing), misal keaktifan dll.
4. Kriteria penilaian laporan:
a. Menggunakan template yang sudah disediakan.
b. Melampirkan hasil praktikum (latihan dan tugas modul) dan screenshot hasil programdan
penjelasannya.
c. Dikerjakan sendiri, jika ketahuan mengcopas, mencontoh, mereplika, menjiplak dll akan
dikenakan sanksi pengosongan nilai laporan.
Penting!
Tetap semangat, jangan menyerah dan pasti bisa jika mau berusaha, jangan lupa juga untuk
terus berdoa agar dapat mencapai hasil yang maksimal, jangan pernah takut untuk bertanya jika
masih ada kebingungan yang melanda, diselingi terus berolah raga, makan yang banyak dan
sehat sesuai 4 sehat 5 sempurna serta minum multivitamin agar tetap bugar :D,