Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Algoritma dan Struktur Data Binary Tree Teknik Informatika Universitas Muhammadiyah Malang SP Ganjil - 2013 Tujuan Instruksional • Mahasiswa mampu menjelaskan mengenai konsep Tree • Mahasiswa mampu membuat dan mendeklarasikan struktur data Tree • Mahasiswa mampu menerapkan dan mengimplementasikan Tree Sub Topik • • • • • Penjelasan Tree Istilah pada tree Binary Tree Jenis Binary Tree ADT Binary tree Linear Lists And Trees • Linear lists are useful for serially ordered data. – (e0, e1, e2, …, en-1) – Days of week. – Months in a year. – Students in this class. • Trees are useful for hierarchically ordered data. – Employees of a corporation. • President, vice presidents, managers, and so on. – Java’s classes. • Object is at the top of the hierarchy. • Subclasses of Object are next, and so on. Hierarchical Data And Trees • The element at the top of the hierarchy is the root. • Elements next in the hierarchy are the children of the root. • Elements next in the hierarchy are the grandchildren of the root, and so on. • Elements that have no children are leaves. Istilah pada Tree Java’s Classes (Part Of Figure 1.1) Object root children of root Number Integer Double Throwable Exception OutputStream FileOutputStream grand children of root RuntimeException great grand child of root Definition • A tree t is a finite nonempty set of elements. • One of these elements is called the root. • The remaining elements, if any, are partitioned into trees, which are called the subtrees of t. Subtrees Object Number Integer Double root Throwable OutputStream Exception FileOutputStream RuntimeException Leaves Object Number Integer Double Throwable OutputStream Exception FileOutputStream RuntimeException Parent, Grandparent, Siblings, Ancestors, Descendants Object Number Integer Double Throwable OutputStream Exception FileOutputStream RuntimeException Levels Object Number Integer Double Level 1 Level 2 Throwable OutputStream Exception FileOutputStream Level 3 RuntimeException Level 4 Caution • Some texts start level numbers at 0 rather than at 1. • Root is at level 0. • Its children are at level 1. • The grand children of the root are at level 2. • And so on. • We shall number levels with the root at level 1. height = depth = number of levels Object Number Integer Double Level 1 Level 2 Throwable OutputStream Exception FileOutputStream Level 3 RuntimeException Level 4 Node Degree = Number Of Children Object 2 1 Number 0 Integer 0 Double 3 Throwable 1 1 Exception RuntimeException OutputStream 0 FileOutputStream 0 Tree Degree = Max Node Degree Object 2 1 Number 0 Integer 0 Double 3 Throwable 1 Exception RuntimeException Degree of tree = 3. 1 OutputStream 0 FileOutputStream 0 Latihan Ancestor (F)? Predesesor (F) ? Descendant (B)? Succesor (B)? Parent (I)? Child (C)? Sibling (G)? Size? Height? Root? Leaf? Degree (C)? Latihan • Jawaban : Ancestor (F) = C,A Predesesor (F) = A,B,C Descendant (B) = D atau E Sucessor (B) = D,E,F,G,H Parent (I) = H Child (C) = F,G,H Sibling (G) = F,H Size = 9 Height = 4 Root = A Leaf = D,E,F,G,I Degree (C) = 3 Latihan Gambarkan tree dari representasi berikut : DF DB KJ KL BA BC H D HK FE FG JI Tentukan : 1. Root 2. Leaf 3. Heigth 4. Child H 5. Parent A Binary Tree Binary Tree • Finite (possibly empty) collection of elements. • A nonempty binary tree has a root element. • The remaining elements (if any) are partitioned into two binary trees. • These are called the left and right subtrees of the binary tree. Differences Between A Tree & A Binary Tree • No node in a binary tree may have a degree more than 2, whereas there is no limit on the degree of a node in a tree. • A binary tree may be empty; a tree cannot be empty. Differences Between A Tree & A Binary Tree • The subtrees of a binary tree are ordered; those of a tree are not ordered. a b a b • Are different when viewed as binary trees. • Are the same when viewed as trees. Contoh Binary Tree • Representasi ekspresi arithmatik Minimum Number Of Nodes • Minimum number of nodes in a binary tree whose height is h. • At least one node at each of first h levels. minimum number of nodes is h Maximum Number Of Nodes • All possible nodes at first h levels are present. Maximum number of nodes = 1 + 2 + 4 + 8 + … + 2h-1 = 2h - 1 Number Of Nodes & Height • Let n be the number of nodes in a binary tree whose height is h. • h <= n <= 2h – 1 • log2(n+1) <= h <= n Full Binary Tree • A full binary tree of a given height h has 2h – 1 nodes. Height 4 full binary tree. Numbering Nodes In A Full Binary Tree • Number the nodes 1 through 2h – 1. • Number by levels from top to bottom. • Within a level number from left to right. 1 2 3 4 8 6 5 9 10 11 12 13 7 14 15 Node Number Properties 1 2 3 4 8 6 5 9 10 11 12 13 7 14 15 • Parent of node i is node i / 2, unless i = 1. • Node 1 is the root and has no parent. Node Number Properties 1 2 3 4 8 6 5 9 10 11 12 13 7 14 15 • Left child of node i is node 2i, unless 2i > n, where n is the number of nodes. • If 2i > n, node i has no left child. Node Number Properties 1 2 3 4 8 6 5 9 10 11 12 13 7 14 15 • Right child of node i is node 2i+1, unless 2i+1 > n, where n is the number of nodes. • If 2i+1 > n, node i has no right child. Akses Elemen untuk Start Level 0 • Asumsi root dimulai dari index 0 : – Anak kiri dari node i berada pada indeks : 2*i+1 – Anak kanan dari node i berada pada indeks : 2*i+2 Struktur Data - Tree 33 Representasi Binary Tree • Binary tree dapat direpresentasikan dengan menggunakan array maupun linked list. Representasi Tree Representasi tree menggunakan array (asumsi root pada index 0) : H D K B F J L A C E G I 0 1 2 3 4 5 6 7 8 9 10 11 Linked Representation root H D K J B L F I A C E leftChild element G rightChild The Class BinaryTreeNode package dataStructures; public class BinaryTreeNode { Object element; BinaryTreeNode leftChild; // left subtree BinaryTreeNode rightChild;// right subtree // constructors and any other methods // come here } Array Representation a 1 2 b 4 3 c 5 e d 8 h tree[] i 9 6 f 10 j a b c d e f g h i j 0 5 10 7 g Latihan a1 b 3 7 c d 15 Right-Skewed Binary Tree a1 b 3 7 c d a - tree[] 0 15 b - - - c - - - - - - - d 5 10 15 Some Binary Tree Operations • • • • • Determine the height. Determine the number of nodes. Make a clone. Determine if two binary trees are clones. Display the binary tree. Binary Tree Traversal Definisi • Penelusuran seluruh node pada binary tree. • Metode : – Preorder – Inorder – Postorder – Level order PreOrder Traversal • Preorder traversal 1. Cetak data pada root 2. Secara rekursif mencetak seluruh data pada subpohon kiri 3. Secara rekursif mencetak seluruh data pada subpohon kanan Preorder Example (visit = print) a b c a b c Preorder Example (visit = print) a b f e d g c h i a b d g h e i c f j j Preorder Of Expression Tree / + * e + a b c d / * + a b - c d + e f Gives prefix form of expression! f InOrder Traversal • Inorder traversal 1.Secara rekursif mencetak seluruh data pada subpohon kiri 2.Cetak data pada root 3.Secara rekursif mencetak seluruh data pada subpohon kanan Inorder Example (visit = print) a b c b a c Inorder Example (visit = print) a b f e d g c h i g d h b e i a f j c j Postorder Traversal • Postorder traversal 1.Secara rekursif mencetak seluruh data pada subpohon kiri 2.Secara rekursif mencetak seluruh data pada subpohon kanan 3.Cetak data pada root Postorder Example (visit = print) a b c b c a Postorder Example (visit = print) a b f e d g c h i g h d i e b j f c a j Postorder Of Expression Tree / + * e + a b c d a b + c d - * e f + / Gives postfix form of expression! f Traversal Applications a b f e d g c h • Make a clone. • Determine height. •Determine number of nodes. i j Latihan • Telusuri pohon biner berikut dengan menggunakan metode pre, in, post, dan level traversal. Latihan 1 + a. 3 * b. 5 - 2 / 8 4 Latihan 2 Level-Order Example (visit = print) a b f e d g c h i a b c d e f g h i j j Contoh : Pohon Ekspresi Implementasi Binary Tree Operasi pada Binary Tree • Operas-operasi yang ada pada binary tree adalah : 1. Deklarasi 2. Pengecekkan kosong (isEmpty) 3. Penambahan node 4. Traversal (penelusuran node) Deklarasi dengan Array • Dengan menggunakan array, prosesnya meliputi : 1. Deklarasi class ArrayBinaryTree 2. Deklarasi variabel array 3. Instansiasi variabel array variabel array digunakan untuk menyimpan node-node yang membentuk binary tree. Yaitu berupa variabel array 1 dimensi. Tipe variabel array akan menentukan jenis data yang dapat disimpan pada binary tree. 4. Deklarasi variabel size (untuk menyimpan jumlah node) 5. Deklarasi variabel last (untuk menyimpan index node terakhir) Contoh program • Deklarasi : public class ArrayBinaryTree //deklarasi class { static Object [] a; //deklarasi array static int last; //deklarasi last static int size=0; //deklarasi size public static void main(String [] args) { a = new Integer [15]; //instansiasi* ..... ..... *contoh : instansiasi variabel array dengan panjang 15 element. isEmpty dengan Array • Digunakan untuk mengecek binary tree dalam kondisi kosong atau terisi node. • Pengecekan menggunakan variabel size. • Mengembalikan true jika size =0. • Mengembalikan false jika nilai size > 0. Contoh program • isEmpty : static boolean isEmpty() { return (size==0); } Penambahan Node dengan Array • Penambahan node dengan menggunakan index. • Ketika terjadi penambahan node terjadi increment nilai pada variabel size. Dan variabel last akan menunjuk index node yang terakhir kali ditambahkan. Contoh program • Penambahan node : static void addNode(int i, int isi) { a[i] = new Integer(isi); size++; last = i; } Traversal dengan Array • Penelusuran (traversal) digunakan untuk menelusuri node pada binary tree satu persatu. • Terdiri dari 3 metode traversal : – Pre-order – In-order – Post-order Contoh program • Penelusuran node (inorder): public static void inOrder(Object [] theArray, int theLast) { a = theArray; if(!isEmpty()) { theInOrder(1); } else System.out.println("Binary Tree Kosong"); } Contoh program • Program rekursif untuk penelusuran subtree : static void theInOrder(int i) { if (i <= last && a[i]!=null) { theInOrder(2 * i); visit(i); theInOrder(2 * i + 1); } } Kunjungan Node • Digunakan untuk mengunjungi node. Proses yang dilakukan adalah mencetak node untuk menandai bahwa node tersebut sudah dikunjungi. Contoh program • Kunjungan/visit node : public static void visit(int i) { System.out.print(a[i] + " "); } Deklarasi dengan Linked list • Dengan menggunakan linked list, prosesnya meliputi : 1. Pembuatan class node (double linked list) 2. Pembuatan class LinkedBinaryTree 3. Deklarasi variabel root bertipe Node 4. Deklarasi variabel size Contoh program • Deklarasi : public class LinkedBTree{ static Node2P root; static int size=0; ..... } isEmpty • Digunakan untuk mengecek binary tree dalam kondisi kosong atau tidak. • Pengecekan dilakukan pada variabel root. • Jika root menunjuk null, kondisi kosong dan mengembalikan nilai true. Sebaliknya, jika root tidak menunjuk null berarti kondisi binary tree tidak kosong dan mengembalikan nilai false. Contoh program • Pengecekan kosong: static boolean isEmpty() { return (root==null); } Penambahan Node • Untuk melakukan penambahan node, terlebih dahulu harus di-create node baru. Node x = new Node(data); • Ketika ada penambahan node terjadi increment nilai pada variabel size. Contoh program • Penambahan node : static void addNode(Node2P baru, Node2P kiri, Node2P kanan) { baru.next = kanan; baru.previous = kiri; size++; } setRoot • Digunakan untuk menandai node mana yang dijadikan sebagai root. static void setRoot(Node2P r) { root = r; } Traversal dengan linkedlist • Penelusuran (traversal) digunakan untuk menelusuri node pada binary tree satu persatu. • Terdiri dari 3 metode traversal : – Pre-order – In-order – Post-order Contoh program • Penelusuran node (postOrder) : static void postOrder() { if(!isEmpty()) thePostOrder(root); else System.out.println("Binary Tree Kosong"); } Contoh program • Program rekursif untuk penelusuran subtree : static void thePostOrder(Node2P node) { if(node != null) { thePostOrder(node.previous); thePostOrder(node.next); System.out.print(node.data + " } } "); Contoh program • Penelusuran node (level order) : static void theLevelOrder(Node2P node) { QueueArray temp = new QueueArray(); temp.inisialisasi(15); temp.enqueue(node); while(temp.jumlah_item >0) { if(node.previous !=null) temp.enqueue(node.previous); if(node.next !=null) temp.enqueue(node.next); System.out.print(node.data + " "); if(!temp.isEmpty()) { temp.dequeue(); node = temp.peekQueue(); } } } Implementasi Binary Search Tree Binary Search Tree (BST) • Binary Search Tree (pohon telusur biner) • Disebut juga Ordered Binary tree yaitu binary tree yang seluruh children dari tiap node terurut. • Data pada subtree kiri lebih kecil dari data pada subtree kanan. Contoh Binary Search Tree • Root = 20 20 10 6 2 40 15 8 30 25 • Bagaimana jika ada penambahan node 13? • Bagaimana jika ada penambahan node 50? • Bagaimana jika ada penambahan node 26? Latihan • Buatlah sebuah Binary Search Tree berdasarkan proses-proses berikut : insert 17, insert 8, insert 32, insert 6, insert 10, insert 21, insert 45, insert 1, insert 7, insert 9, insert 26, insert 37, insert 50. Operasi Binary Search Tree • Operasi-operasi yang dilakukan pada binary search tree meliputi : 1. Penambahan node 2. Penghapusan node 3. Pencarian node Penambahan BST • Penambahan node pada BST harus mengikuti aturan minMax, dimana node yang bernilai lebih kecil dari root diletakkan pada subtree sebelah kiri sedangkan node yang bernilai lebih besar diletakkan pada subtree sebelah kanan. Jika ada nilai yang sama maka node tersebut di-overwrite. Contoh program • Penambahan : Node2P insert(int x, Node2P t) { if (t == null) { t = new Node2P (x, null, null); } else if (x < t.data) { t.previous = insert (x, t.previous); } else if (x > t.data) { t.next = insert (x, t.next); } else { t=t; } return t; } Penghapusan BST Ada 3 kasus : Elemen ada di leaf/daun. Elemen yang memiliki degree 1. Elemen yang memiliki degree 2. Penghapusan Node Daun (Node 7) 20 10 6 2 40 15 8 30 18 25 35 7 Remove a leaf element. key = 7 Penhapusan Node Daun (Node 35) 20 10 6 2 40 15 8 30 18 25 35 7 Remove a leaf element. key = 35 Penghapusan Node Ber-degree 1 20 10 6 2 40 15 8 30 18 25 35 7 Remove from a degree 1 node. key = 40 Penghapusan Node Ber-degree 1 20 10 6 2 40 15 8 30 18 25 35 7 Remove from a degree 1 node. key = 15 Penghapusan Node Ber-degree 2 20 10 6 2 40 15 8 30 18 25 35 7 Remove from a degree 2 node. key = 10 Remove From A Degree 2 Node 20 10 6 2 40 15 8 30 18 25 35 7 Replace with largest key in left subtree (or smallest in right subtree). Penghapusan Node Ber-degree 2 20 10 6 2 40 15 8 30 18 25 35 7 Replace with largest key in left subtree (or smallest in right subtree). Penghapusan Node Ber-degree 2 20 8 6 2 40 15 8 30 18 25 35 7 Replace with largest key in left subtree (or smallest in right subtree). Latihan 20 10 6 2 40 15 8 30 18 25 35 7 Remove from a degree 2 node. key = 20 Penghapusan Node Ber-degree 2 20 10 6 2 40 15 8 30 18 25 35 7 Replace with largest in left subtree. Penghapusan Node Ber-degree 2 20 10 6 2 40 15 8 30 18 25 35 7 Replace with largest in left subtree. Penghapusan Node Ber-degree 2 18 10 6 2 40 15 8 30 18 25 35 7 Replace with largest in left subtree. Hasil Akhir 18 10 6 2 15 8 7 40 30 25 35 Contoh program • Penghapusan: Node2P remove(int x, Node2P t) { if (t == null) t=null; if (x < t.data) { t.previous = remove(x, t.previous); } else if (x > t.data) { t.next = remove(x, t.next); } else if (t.previous != null && t.next != null) { t.data = findMin(t.next).data; t.next = removeMin(t.next); } else { t = (t.previous != null) ? t.previous : t.next; } return t; } Contoh program • Penghapusan node terkecil : Node2P removeMin(Node2P t) { if (t == null) t=null; if (t.previous != null) { t.previous = removeMin (t.previous); } else { t = t.next; } return t; } Contoh program Pencarian Node terkecil : Node2P findMin (Node2P t) { if (t == null) t=null; while (t.previous != null) { t = t.previous; } return t; } Pustaka • Sartaj Sahni , “Data Structures & Algorithms”, Presentation L20-24. • Mitchell Waite, “Data Structures & Algorithms in Java”, SAMS, 2001