You are on page 1of 9

3.

Binripuu, Java-toteutus

/*-------------------------------------------------------------/ / Rajapinta SearchTree: binrisen hakupuun ksittelyrajapinta / / / / Metodit: / / / / void insert( Comparable x ); / / - solun lisminen puuhun / / void remove( Comparable x ); / / - solun poistaminen puusta / / void removeMin(); / / - pienint data-alkiota vastaavan solun poistaminen / / Comparable find( Comparable x ); / / - solun etsiminen / / Comparable findMin(); / / - pienint data-alkiota vastaavan solun etsiminen / / Comparable findMax(); / / - suurinta data-alkiota vastaavan solun etsiminen / / boolean isEmpty(); / / - testi, onko puu tyhj / / void makeEmpty(); / / - puun tyhjentminen / / void printTree(); / / - puun tulostaminen / / / / Huomautuksia: / / - rahjapinta on sijoitettava samaan pakkaukseen kuin luokka / / BstNode ja tmn rajapinnan implementoiva luokka, / / esimerkiksi BST / / - rajapinta SearchTree mahdollistaa usean eri hakupuun / / toteutuksen, esim. BST, AVL, Red-Black Tree ym. / / - rajapinta on otettu teoksesta Weiss M. A: Data Structures / / & Problem Solving Using Java / / / / T. Harju 2002.10 / /-------------------------------------------------------------*/ public interface SearchTree {

/*-------------------------------------------------------------/ / Luokka BstNode: binrisen hakupuun (BST) solu / / / / Kentt: / / / / Comparable item : solun data / / BstNode left : viite solun vasempaan lapsisoluun / / BstNode right : viite solun oikeaan lapsisoluun / / / / Konstruktorit: / / / / BstNode( Comparable it ) / / BstNode( Comparable it, BstNode lt, BstNode rt ) / / / / Metodit: / / - ei metodeja / / / / Huomautuksia: / / - luokka on sijoitettava samaan pakkaukseen kuin / / rajapinta SeachTree ja luokka BST / / - luokka yhdess rajapinnan SearchTree kanssa mahdollistaa / / muunkin hakupuun kuin perus-BST:n toteutuksen. Tss esim./ / on varauduttu AVL:n toteutukseen: luokka sislt, tosin / / pois kommentoituna, AVL:n toteutusta helpottavan kentn / / "height" / / - luokan toteutus perustuu teoksessa Weiss M. A: Data / / Structures & Problem Solving Using Java julkaistuun / / koodiin. / / / / T. Harju 2002.10 / /-------------------------------------------------------------*/

class BstNode { Comparable item; BstNode left; BstNode right; // int height = 0; //Varauduttu AVL:n

void insert( Comparable x ); void remove( Comparable x ); void removeMin(); Comparable find( Comparable x ); Comparable findMin(); Comparable findMax(); boolean isEmpty(); void makeEmpty(); void printTree(); }

BstNode( Comparable it, BstNode lt, BstNode rt ) { item = it; left = lt; right = rt; } BstNode( Comparable it) { this( it, null, null ); } }

/*-------------------------------------------------------------/ / Luokka BST: binrisen hakupuun (BST) implementointi toteut- / / tamalla rajapinta SearchTree / / / / Kentt: / / / / BstNode root : BST:n juurisolu / / / / Konstruktorit: / / / / BST() / / - luo tyhjn BST:n, jossa root = null / / / / Rajapinnan metodit: / / / / void insert( Comparable x ); / / - solun lisminen puuhun / / void remove( Comparable x ); / / - solun poistaminen puusta / / void removeMin(); / / - pienint data-alkiota vastaavan solun poistaminen / / Comparable find( Comparable x ); / / - solun etsiminen / / Comparable findMin(); / / - pienint data-alkiota vastaavan solun etsiminen / / Comparable findMax(); / / - suurinta data-alkiota vastaavan solun etsiminen / / boolean isEmpty(); / / - testi, onko puu tyhj / / void makeEmpty(); / / - puun tyhjentminen / / void printTree(); / / - puun tulostaminen / / / / Toteutustapa: / / Edell olevat metodit ovat kaikki julkisia ja muodostavat / / siten julkisen ohjelmointirajapinnan. Varsinainen toteutus / / on kuitenkin ktketty muilta kuin luokan perillisill paitsi/ / yksinkertaisimmilla metodeilla, esim. isEmpty(). Rajapinta- / / metodit vain kutsuvat toteutusmetodeja, jotka ovat nky/ / vyydeltn "protected". Katso tm varsinainen toteutus / / koodista. / / / / Huomautuksia: / / - luokka on sijoitettava samaan pakkaukseen kuin luokka / / BstNode ja rajapinta SearchTree / / - luokan toteutus perustuu teoksessa Weiss M. A: Data / / Structures & Problem Solving Using Java julkaistuun / / koodiin. / / / / T. Harju 2002.10 / /-------------------------------------------------------------*/

public class BST implements SearchTree { protected BstNode root; public BST() { root = null; } /*--- Rajapinnan SearcTree toteutus ---*/

public void insert( Comparable x ) { root = insert( x, root ); } public void remove( Comparable x ) { root = remove( x, root ); } public void removeMin() { root = removeMin( root ); } public Comparable find( Comparable x ) { return find( x, root ).item; } public Comparable findMin() { return findMin( root ).item; } public Comparable findMax() { return findMax( root ).item; } public boolean isEmpty() { return root == null; } public void makeEmpty() { root = null; } public int height() { return height( root ); } public void printTree() { printTree( root ); } // BST:n korkeus, ei sislly rajapintaan

/*--- Sisiset metodit: varsinainen toteutuskoodi ---*/ protected BstNode insert( Comparable x, BstNode t ) { if ( t == null ) t = new BstNode( x, null, null ); else if ( x.compareTo( t.item ) < 0 ) t.left = insert( x, t.left ); else if ( x. compareTo( t.item ) > 0 ) t.right = insert( x, t.right ); else System.out.println( "BST insert: duplicate item" ); return t; } protected BstNode remove( Comparable x, BstNode t ) { if ( t == null ) { System.out.println( "BST remove: item not found" ); return t; } if ( x.compareTo( t.item ) < 0 ) t.left = remove( x, t.left ); else if ( x.compareTo( t.item ) > 0 ) t.right = remove( x, t.right ); else if ( t.left != null && t.right != null ) { t.item = findMin( t.right ).item; t.right = removeMin( t.right ); } else t = ( ( t.left != null ) ? t.left : t.right ); return t; } protected BstNode removeMin( BstNode t ) { if ( t == null ) { System.out.println( "BST removeMin: item not found" ); return t; } if ( t.left != null ) t.left = removeMin( t.left ); else t = t.right; return t; } protected BstNode find( Comparable x, BstNode t ) { while ( t != null ) if ( x.compareTo( t.item ) < 0 ) t = t.left; else if ( x.compareTo( t.item ) > 0 ) t = t.right; else return t; System.out.println( "BST find: item not found" ); return t; }

protected BstNode findMin( BstNode t ) { if ( t != null ) System.out.println( "BST findMin: item not found" ); while ( t.left != null ) t = t.left; return t; } protected BstNode findMax( BstNode t ) { if ( t != null ) System.out.println( "BST findMax: item not found" ); while ( t.right != null ) t = t.right; return t; } protected int height( BstNode t ) { int u, v; if ( t == null ) return -1; else { u = height( t.left ); v = height( t.right ); return ( u > v ) ? u + 1 : v + 1; } } protected void printTree( BstNode t ) { if ( t.left != null ) printTree( t.left ); for ( int i = 0; i < 2*height( t ); ++i ) System.out.print( " " ); System.out.println( t.item ); if ( t.right != null ) printTree( t.right ); } }

public class BstDemo { public static void main( String[] args ) { SearchTree puu = new BST(); System.out.println( "Anna BST:hen sijoitettavat luvut, lopuksi 999" ); System.out.print( ": " ); int luku = Lue.kluku(); while ( luku != -999 ) { puu.insert( new Integer( luku ) ); System.out.print( ": " ); luku = Lue.kluku(); } puu.printTree(); } }

4.
/* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /*

BST, C-toteutus
---------------------------------------------------------------- */ BST.H - binrisen hakupuun (Binary Search Tree) ksittelyyn */ liittyvi mrittelyj. */ */ Kytt: */ - omaan ohjelmaan #include "bst.h", jonka on oltava */ hakemistossa, mist kntj sen lyt */ - tiedosto bst.c linkitettv mukaan ohjelmaan */ */ Sislt: */ */ insNode() : lis noden BST:hen, mys tyhjn */ find() : etsii noden BST:st */ findMin() : etsii BST:n pienimmn data-alkion noden */ findMax() : etsii BST:n suurimman data-alkion noden */ delNode() : poistaa noden BST:st */ delBST : poistaa koko BST:n */ height() : palauttaa BST:n korkeuden */ printBST() : tulostaa BST:n sislln sisjrjstyksess */ */ Teokseen Weiss: Data Structures and Algorithm Analysis perustuen */ implementoinut Timo Harju 1999.11, 2000.12 */ ---------------------------------------------------------------- */

/* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /*

---------------------------------------------------------------- */ BST.C - binrisen hakupuun (Binary Search Tree) ksittelyyn */ liittyvi funktioita */ */ Kytt: */ - omaan ohjelmaan #include "bst.h", jonka on oltava */ hakemistossa, mist kntj sen lyt */ - tm tiedosto bst.c linkitettv mukaan ohjelmaan */ */ Sislt: */ */ insNode() : lis noden BST:hen, mys tyhjn */ find() : etsii noden BST:st */ findMin() : etsii BST:n pienimmn data-alkion noden */ findMax() : etsii BST:n suurimman data-alkion noden */ delNode() : poistaa noden BST:st */ delBST() : poistaa koko BST:n */ height() : palauttaa BST:n korkeuden */ printBST() : tulostaa BST:n sislln sisjrjstyksess */ */ Teokseen Weiss: Data Structures and Algorithm Analysis perustuen */ implementoinut Timo Harju 1999.11, 2000.12 */ ---------------------------------------------------------------- */

#ifndef _BST.H #define _BST.H /* ---------------------------------------------------------------- */ typedef int item_type; typedef struct node *link; struct node { item_type item; link left; link right; }; typedef link BST; typedef struct node Node; /* BST:n datan tyyppi */ /* Pointteri nodeen */ /* Node: */ /* data */ /* pointteri vasempaan oksaan */ /* ja oikeaan oksaan */

#include <stdio.h> #include <stdlib.h> #include "bst.h" link insNode( BST T, item_type a ) { if ( T == NULL ) { if ( ( T = ( link ) malloc( sizeof( struct node ) ) ) == NULL ) { printf( "insNode: muistin varaaminen eponnistui\n" ); exit(1); } T->item = a; T->left = T->right = NULL; } else if ( a < T->item ) T->left = insNode( T->left, a ); else if ( a > T->item ) T->right = insNode( T->right, a ); return T; } link find( BST T, item_type x ) { if ( T == NULL ) return T; if ( x < T->item ) return find( T->left, x ); else if ( x > T->item ) return find( T->right, x ); else return T; }

/* Vaihtoehtoinen nimi pointterille */ /* ja itse nodelle */

/* Funktioiden prototyypit */ link insNode( BST T, item_type a ); link find( BST T, item_type x ); link findMin( BST T ); link findMax( BST T ); link delNode( BST T, item_type a ); void delBST( BST T ); int height( BST T ); void printBST( BST T ); #endif

link findMin( BST T ) { if ( T != NULL ) while( T->left ) T = T->left; return T; } link findMax( BST T ) { if ( T != NULL ) while( T->right ) T = T->right; return T; } link delNode( BST T, item_type a ) { link temp, child; if ( T == NULL ) printf( "Tuhottavaa ei lydy" else if ( a < T->item ) T->left = delNode( T->left, a else if ( a > T->item ) T->right = delNode( T->right, else if ( T->left && T->right ) { temp = findMin( T->right ); T->item = temp->item; T->right = delNode( T->right, } else { temp = T; if ( T->left == NULL ) child = T->right; if ( T->right == NULL ) child = T->left; free( temp ); return child; } return T; } void delBST( BST T ) { link p, q; if ( T != NULL ) { p = T->left; q = T->right; free( T ); delBST( p ); delBST( q ); } }

int height( BST T ) { int u, v; if ( T == NULL ) return -1; else { u = height( T->left ); v = height( T->right ); if ( u > v ) return u+1; else return v+1; } } void printBST( BST T ) { int n, i; if ( T != NULL ) { printBST( T->left ); n = height( T ); for ( i = 0 ; i < 2 * n; ++i ) printf( " " ); printf( "%d\n", T->item ); printBST( T->right ); } }

); ); a );

/* Tss yritetn saada */ /* tulostus edes vhn */ /* puuta muistuttavaksi */

T->item ); /* /* /* /* /* /* -----------------------------------------------------------TIETORAKENTEET JA ALGORITMIT: BSTDemo Varsinaiset BST:n ksittelyrutiinit ovat tiedostoissa bst.h (tietotyypit ja funktioiden prototyypit) sek bst.c (koodi) T. Harju 1999.11, 2000.12 -----------------------------------------------------------*/ */ */ */ */ */

#include <stdio.h> #include <conio.h> #include "bst.h" void main( void ) { BST Tree = NULL, p; int val, luku; clrscr(); printf( "BST:n (Binary Search Tree) ksittely\n\n"); printf( "Anna puuhun sijoitettavat luvut, lopuksi -9999\n" ); printf( ": " ); scanf( "%d", &luku ); while ( luku != -9999 ) { Tree = insNode( Tree, luku ); printf( ": " ); scanf( "%d", &luku ); } printBST( Tree ); printf( "Puun korkeus on %d\n", height( Tree ) ); printf( "\n\nPress any key .." ); getch();

/* Sitten vaan kokeillaan lisyst, poistoa ja koko listan hvittmist. */ /* Siin sivussa tulee etsiminenkin testatuksi. */ do { do { clrscr(); printf( "Lisys .............. printf( "Poisto .............. printf( "BST:n tuhoaminen .. . printf( "Lopetus ............. printf( "\nValintasi: " ); scanf( "%d", &val ); } while ( ( val < 0 ) || ( val > switch ( val ) { case 1: /* Lisys */ printBST( Tree ); printf( "Puun korkeus on %d\n", height( Tree printf( "Anna listttv alkio: " ); scanf( "%d", &luku ); Tree = insNode( Tree, luku ); printBST( Tree ); printf( "Puun korkeus on %d\n", height( Tree printf( "\n\nPress any key .." ); getch(); break; case 2: /* Poisto */ printBST( Tree ); printf( "Puun korkeus on %d\n", height( Tree printf( "Mik alkio poistetaan: " ); scanf( "%d", &luku ); p = find( Tree, luku ); if ( p == NULL ) { printf( "Ei lydy!" ); printf( "\n\nPress any key .." ); getch(); break; } Tree = delNode( Tree, luku ); printBST( Tree ); printf( "Puun korkeus on %d\n", height( Tree printf( "\n\nPress any key .." ); getch(); break; case 3: /* Puun hvittminen */ delBST( Tree ); Tree = NULL; printBST( Tree ); printf( "Puun korkeus on %d\n", height( Tree printf( "\n\nPress any key .." ); getch(); break; default: break; } } while( val != 0 ); }

6.

BST, vaatimaton java-toteutus

/* Luokka BST: vhn BST-luokan alkua / / TH 2003.10 */ 1\n" 2\n" 3\n" 0\n" ); ); ); );

class Node { Comparable item; Node left; Node right; public Node() { item = null; left = right = null; } ) ); } public class BST { private Node root; ) ); public BST() { root = null; }

// BST:n solu: data + linkit oksiin // Comparable on Javassa mr. rajapinta

3 ) );

// Solun konstruktori

// Puun juuri // Konstruktori

) );

// Solun lisys public Node insNode( Node T, Comparable a ) { if ( T == null ) { T = new Node(); T.item = a; T.left = T.right = null; } else if ( a.compareTo( T.item ) < 0 ) T.left = insNode( T.left, a ); else if (a.compareTo( T.item ) > 0 ) T.right = insNode( T.right, a ); return T; } public Node getRoot() { return root; } public void setRoot( Node p ) { root = p; } // Palauttaa juuren

) );

// Asettaa juuren

) );

void prTree( Node p, int h ) { if ( p != null ) { prTree( p.right, h + 1 ); for ( int i = 0; i < h; ++i ) System.out.print( " " ); System.out.println( p.item ); prTree( p.left, h + 1 ); } } }

// Tulostetaan puu

// sisjrjestyksess // jossakin mrin puun // muodossa

/* Testiohjelma luokan BST kokeilemiseksi / / TH 2003.10 */

6.

PQ, C-toteutus
/* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* ---------------------------------------------------------------PQ.H - priorisoidun jonon (Priority Queue) ksittelyyn liittyvi mrittelyj, PQ:n toteutus taulukossa olevana binrisen kasana (heap) */ */ */ */ */ Kytt: */ - omaan ohjelmaan #include "pq.h", jonka on oltava */ hakemistossa, mist kntj sen lyt */ - tiedosto pq.c linkitettv mukaan ohjelmaan */ */ Sislt: */ */ creaPQ() : luo PQ:n */ insert() : lis alkion PQ:un */ delMin() : poistaa PQ:n pienimmn alkion */ printPQ() : tulostaa PQ:n (vast. puun tasojrjestyksess ) */ delPQ() : tuhoaa PQ:n */ */ Teokseen Weiss: Data Structures and Algorithm Analysis perustuen */ implementoinut Timo Harju 1999.12, 2000.12 */ ---------------------------------------------------------------- */

public class BSTdemo { public static void main( String[] args ) { BST puu = new BST(); // Luodaan BST

System.out.println( "Anna BST:hen sijoitettavat kokonaisluvut yksitellen." ); System.out.println( "Anna lopuksi -999" ); System.out.print( ": " ); int luku= Lue.kluku(); if ( luku != -999 ) {

// Ensimminen sijoitettava

// Tehdn siit juuri puu.setRoot( puu.insNode( puu.getRoot(), new Integer( luku ) ) ); puu.prTree( puu.getRoot(), 0 ); System.out.println( "" ); System.out.print( ": " ); luku= Lue.kluku(); while ( luku != -999 ) { puu.insNode( puu.getRoot(), new Integer( luku ) ); puu.prTree( puu.getRoot(), 0 ); System.out.println( "" ); System.out.print( ": " ); luku= Lue.kluku(); } } } }

#ifndef _PQ.H #define _PQ.H typedef int item_type; struct pqStruct { int maxSize; int size; item_type *items; }; typedef struct pqStruct *PQ; /* PQ:n datan tyyppi */

/* PQ:n maksimi alkiomr */ /* PQ:n todellinen alkiomr */ /* Pointteri PQ:n datataulukkoon */

/* Pointterityyppi PQ:un */

/* Funktioiden prototyypit */ PQ creaPQ( int n ) ; void insert( PQ H, item_type a ); item_type delMin( PQ H ); void printPQ( PQ H ); void delPQ( PQ H ); #endif

/* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /*

---------------------------------------------------------------PQ.C - priorisoidun jonon (Priority Queue) ksittelyyn liittyvi funktioita, PQ:n toteutus taulukossa olevana binrisen kasana (heap)

*/ */ */ */ */ Kytt: */ - omaan ohjelmaan #include "pq.h", jonka on oltava */ hakemistossa, mist kntj sen lyt */ - tm tiedosto pq.c linkitettv mukaan ohjelmaan */ */ Sislt: */ */ creaPQ() : luo PQ:n */ insert() : lis alkion PQ:un */ delMin() : poistaa PQ:n pienimmn alkion */ printPQ() : tulostaa PQ:n (vast. puun tasojrjestyksess ) */ delPQ() : tuhoaa PQ:n */ */ Teokseen Weiss: Data Structures and Algorithm Analysis perustuen */ implementoinut Timo Harju 1999.12, 2000.12 */ ---------------------------------------------------------------- */

void insert( PQ H, item_type a ) { int i; if ( H->size == H->maxSize ) printf( "PQ on tynn\n" ); else { i = ++H->size; while( H->items[i/2] > a ) { H->items[i] = H->items[i/2]; i /= 2; } H->items[i] = a; } } item_type delMin( PQ H ) { int i, child; item_type mini, last;

#include <stdio.h> #include <stdlib.h> #include "PQ.H" #ifndef MIN_DATA #define MIN_DATA -32767 #endif PQ creaPQ( int n ) { PQ H; H = ( PQ ) malloc( sizeof( struct pqStruct ) ); if ( H == NULL ) { printf( "PQ:n muistinvaraus ei onnistunut\n" ); exit( 1 ); } H->items = ( item_type * ) malloc( ( n + 1 ) * sizeof( item_type ) ); if ( H->items == NULL ) { printf( "PQ:n datan muistinvaraus ei onnistunut\n" ); exit( 2 ); } H->maxSize = n; H->size = 0; H->items[0] = MIN_DATA; return H; }

/* Pienin mahdollinen data-alkio (int) */

if ( H->size == 0 ) { printf( "PQ on tyhj\n" ); return H->items[0]; } mini = H->items[1]; last = H->items[H->size--]; for ( i = 1; 2*i <= H->size; i = child ) { child = 2*i; if ( ( child != H->size ) && ( H->items[child+1] < H->items[child] ) ) ++child; if ( last > H->items[child] ) H->items[i] = H->items[child]; else break; } H->items[i] = last; return mini; } void printPQ( PQ H ) { int i; for ( i = 1; i <= H->size; ++i ) printf( "%d ", H->items[i] ); }

void delPQ( PQ H ) { free( H->items ); free( H ); H = NULL; }

You might also like