Implementazione Java di Alberi Binari. A.A. 16/17 DA1 - Andrea Pietracaprina 1

Similar documents
Implementazione Alberi Binari. mediante. Linked Structure ( 7.3.4)

Examples

CSE Summer Assignment #2

interface Position<E> { E getelement() throws IllegalStateExcept..; }

Binary trees. Binary trees. Binary trees

Universidad Carlos III de Madrid

Outline. Definitions Traversing trees Binary trees

CPSC 35 Midterm Exam

Lists. Outline. COMP9024: Data Structures and Algorithms. Lists. Array List ADT. Array-Based Implementation. Array lists Node lists Iterators

csci 210: Data Structures Trees

Binary Node. private Object element; private BinaryNode left; private BinaryNode right; 02/18/03 Lecture 12 1

Figure 18.4 A Unix directory. 02/10/04 Lecture 9 1

Binary Search Trees. BinaryTree<E> Class (cont.) Section /27/2017

Figure 18.4 A Unix directory. 02/13/03 Lecture 11 1

DataStruct 7. Trees. Michael T. Goodrich, et. al, Data Structures and Algorithms in C++, 2 nd Ed., John Wiley & Sons, Inc., 2011.

Binary Trees Fall 2018 Margaret Reid-Miller

CmpSci 187: Programming with Data Structures Spring 2015

CS 206 Introduction to Computer Science II

tree nonlinear Examples

Surfing Ada for ESP Part 2

Topic 14. The BinaryTree ADT

Maximum Grade: 5 points out of 10 of the exam.

CS24 Week 8 Lecture 1

CS 314 Final Fall 2011

CS 206 Introduction to Computer Science II

Sample Questions for Midterm Exam 2

Tree traversals and binary trees

Generic BST Interface

IMPLEMENTING BINARY TREES

protected BinaryNode root; } 02/17/04 Lecture 11 1

The heap is essentially an array-based binary tree with either the biggest or smallest element at the root.

Title Description Participants Textbook

Trees. Make Money Fast! Bank Robbery. Stock Fraud. Ponzi Scheme Goodrich, Tamassia. Trees 1

Linked List Nodes (reminder)

CMPSCI 187: Programming With Data Structures. Lecture #28: Binary Search Trees 21 November 2011

Lecture 16. Lecture

Recursion. Example 1: Fibonacci Numbers 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,

Trees Chapter 19, 20. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

CSCI 136 Data Structures & Advanced Programming. Lecture 22 Spring 2018 Profs Bill & Jon

Priority queues. Priority queues. Priority queue operations

CS : Data Structures

If you took your exam home last time, I will still regrade it if you want.

Computer Science 136 Exam 2

Programmi di utilità

ITI Introduction to Computing II

STUDENT LESSON AB30 Binary Search Trees

The tree data structure. Trees COL 106. Amit Kumar Shweta Agrawal. Acknowledgement :Many slides are courtesy Douglas Harder, UWaterloo

Module 6: Binary Trees

Motivation Computer Information Systems Storage Retrieval Updates. Binary Search Trees. OrderedStructures. Binary Search Tree

The Problem with Linked Lists. Topic 18. Attendance Question 1. Binary Search Trees. -Monty Python and The Holy Grail

Outline. An Application: A Binary Search Tree. 1 Chapter 7: Trees. favicon. CSI33 Data Structures

Outline. iterator review iterator implementation the Java foreach statement testing

Principles of Computer Science

CS 3 Introduction to Software Engineering. 5: Iterators

Lecture 23: Binary Search Trees

CS 206 Introduction to Computer Science II

Priority queues. Priority queues. Priority queue operations

Data Structures. Giri Narasimhan Office: ECS 254A Phone: x-3748

Definitions A A tree is an abstract t data type. Topic 17. "A tree may grow a. its leaves will return to its roots." Properties of Trees

Trees. Make Money Fast! Bank Robbery. Ponzi Scheme. Stock Fraud. 02/06/2006 Trees 1

CMPT 225. Red black trees

Programming II (CS300)

ITI Introduction to Computing II

Chapter 11.!!!!Trees! 2011 Pearson Addison-Wesley. All rights reserved 11 A-1

Chapter 11.!!!!Trees! 2011 Pearson Addison-Wesley. All rights reserved 11 A-1

CSE 214 Computer Science II Heaps and Priority Queues

Points off Total off Net Score. CS 314 Final Exam Spring 2017

CS 314 Exam 2 Spring 2016

ITI Introduction to Computing II

D. Do inorder traversal on tree, values in ascending order, no repeats.

Heaps. Heaps. A heap is a complete binary tree.

Week 2. TA Lab Consulting - See schedule (cs400 home pages) Peer Mentoring available - Friday 8am-12pm, 12:15-1:30pm in 1289CS

Binary Search Tree 1.0. Generated by Doxygen Mon Jun :12:39

The Binary Search Tree ADT

Trees. Data structures and Algorithms. Make Money Fast! Bank Robbery. Stock Fraud. Ponzi Scheme

Computer Science II Fall 2009

Object Oriented Software Design

1 public class BinaryTree<E extends Comparable<E>> { 2 private Node<E> root; 3 4 public BinaryTree (){ 5 root = null; 6 } 7 8 private BinaryTree

CS 314 Exam 2 Fall 2017

" Which data Structure to extend to create a heap? " Two binary tree extensions are needed in a heap. n it is a binary tree (a complete one)

CSE 143 Sp04 Final Exam Sample Solution Page 1 of 12

Binary Tree Implementation

a graph is a data structure made up of nodes in graph theory the links are normally called edges

Priority Queue. How to implement a Priority Queue? queue. priority queue

Summer Session 2004 Prelim I July 12, CUID: NetID:

Topic 18 Binary Trees "A tree may grow a thousand feet tall, but its leaves will return to its roots." -Chinese Proverb

9/26/2018 Data Structure & Algorithm. Assignment04: 3 parts Quiz: recursion, insertionsort, trees Basic concept: Linked-List Priority queues Heaps

4.5 Minimum Spanning Tree. Minimo albero di copertura o ricoprimento

Compiling expressions

CS : Data Structures

Data Structure Lecture#10: Binary Trees (Chapter 5) U Kang Seoul National University

Data Structures in Java

Expression Trees and the Heap

CE 221 Data Structures and Algorithms

Data Structures Brett Bernstein

Unit 9 Practice Test (AB27-30)

York University AK/ITEC INTRODUCTION TO DATA STRUCTURES. Final Sample II. Examiner: S. Chen Duration: Three hours

CS 307 Final Fall 2009

CSC 321: Data Structures. Fall 2016

CSE143 Summer 2008 Final Exam Part B KEY August 22, 2008

Transcription:

Implementazione Java di Alberi Binari A.A. 16/17 DA1 - Andrea Pietracaprina 1

Idea: struttura linkata Un nodo contiene Element Parent node Left child node Right child node B B A D A D C E C E A.A. 16/17 DA1 - Andrea Pietracaprina 2

Schema interfacce e classi Position<E> extends BTPosition<E> implements BTNode<E> usa Tree<E> usa extends BinaryTree<E> implements LinkedBinaryTree<E> PositionList<E> extends Iterable<E> implements NodePositionList<E> N.B. In [GTG14] implementazione alternativa A.A. 16/17 DA1 - Andrea Pietracaprina 3

Interfaccia BinaryTree public interface BinaryTree<E> extends Tree<E> { public Position<E> left(position<e> v); public Position<E> right(position<e> v); public Position<E> sibling(position<e> v); public boolean hasleft(position<e> v); public boolean hasright(position<e> v); N.B. Eredita i metodi dell interfaccia Tree<E> A.A. 16/17 DA1 - Andrea Pietracaprina 4

Interfaccia BTPosition public interface BTPosition<E> extends Position<E> { public void setelement(e o) ; public BTPosition<E> getleft() ; public void setleft(btposition<e> v) ; public BTPosition<E> getright() ; public void setright(btposition<e> v) ; public BTPosition<E> getparent() ; public void setparent(btposition<e> v) ; N.B. Eredita dall interfaccia Position<E> il metodo E element() A.A. 16/17 DA1 - Andrea Pietracaprina 5

Classe BTNode public class BTNode<E> implements BTPosition<E> { private E element; // element stored at this node private BTPosition<E> left, right, parent; // adjacent nodes public BTNode(E element, BTPosition<E> parent, BTPosition<E> left, BTPosition<E> right) { setelement(element); setparent(parent); setleft(left); setright(right); public E element() { return element; public void setelement(e o) { element=o; public BTPosition<E> getleft() { return left; public void setleft(btposition<e> v) { left=v; public BTPosition<E> getright() { return right; public void setright(btposition<e> v) { right=v; public BTPosition<E> getparent() { return parent; public void setparent(btposition<e> v) { parent=v; A.A. 16/17 DA1 - Andrea Pietracaprina 6

Classe LinkedBinaryTree public class LinkedBinaryTree<E> implements BinaryTree<E> { protected BTPosition<E> root; // reference to the root protected int size; // number of nodes /* Constructor */ public LinkedBinaryTree() { root = null; size = 0; protected BTPosition<E> createnode(e element, BTPosition<E> parent, BTPosition<E> left, BTPosition<E> right) { return new BTNode<E>(element,parent,left,right); public Position<E> addroot(e e) throws NonEmptyTreeException{ if (!isempty) throw new NonEmptyTreeException( Tree already has a root ); size = 1; root = createnode(e,null,null,null); return root; N.B.L uso di BTNode è confinato. al metodo createnode A.A. 16/17 DA1 - Andrea Pietracaprina 7

Classe LinkedBinaryTree protected BTPosition<E> checkposition(position<e> v) throws InvalidPositionException{ if (v == null!(v instanceof BTPosition)) throw new InvalidPositionException( Position is invalid"); return (BTPosition<E>) v; A.A. 16/17 DA1 - Andrea Pietracaprina 8

Classe LinkedBinaryTree public Position<E> root() throws EmptyTreeException{ if (root == null) throw new EmptyTreeException( Tree is empty"); return root; public boolean hasleft(position<e> v) throws InvalidPositionException{ BTPosition<E> vv = checkposition(v); return (vv.getleft()!=null);; public Position<E> left(position<e> v) throws InvalidPositionException, BoundaryViolationException { BTPosition<E> vv = checkposition(v); Position<E> leftpos = vv.getleft(); if (leftpos == null) throw new BoundaryViolationException( No left child"); return leftpos; A.A. 16/17 DA1 - Andrea Pietracaprina 9

Classe LinkedBinaryTree public Position<E> insertleft(position<e> v, E e) throws InvalidPositionException { BTPosition<E> vv = checkposition(v); Position<E> leftpos = vv.getleft(); if (leftpos!= null) throw new InvalidPositionException("Node already has a left child"); BTPosition<E> w = createnode(e, vv, null, null); vv.setleft(w); size++; return w; Oss. Questo metodo (e l analogo metodo insertright) permette di aggiungere all albero un nuovo nodo, contenete un dato elemento e, come figlio sinistro (risp., destro) di un dato nodo v. Il metodo remove nel prossimo lucido invece serve per eliminare un nodo che ha al più un figlio A.A. 16/17 DA1 - Andrea Pietracaprina 10

Classe LinkedBinaryTree public E remove(position<e> v) throws InvalidPositionException { BTPosition<E> vv = checkposition(v); BTPosition<E> leftpos = vv.getleft(); BTPosition<E> rightpos = vv.getright(); if (leftpos!= null && rightpos!= null) throw new InvalidPositionException("Cannot remove node"); BTPosition<E> ww; // the only child of v, if any if (leftpos!= null) ww = leftpos; else if (rightpos!= null) ww = rightpos; else ww = null; if (vv == root) { if (ww!= null) ww.setparent(null); root = ww; else { BTPosition<E> uu = vv.getparent(); if (vv == uu.getleft()) uu.setleft(ww); else uu.setright(ww); if(ww!= null) ww.setparent(uu); size--; return v.element(); N.B. Si restituisce l elemento contenuto nel nodo rimosso A.A. 16/17 DA1 - Andrea Pietracaprina 11

Classe LinkedBinaryTree protected void preorderpositions(position<e> v, PositionList<Position<E>> pos) throw InvalidPositionException { pos.addlast(v); // visit node v if (hasleft(v)) preorderpositions(left(v), pos); // recurse on left child if (hasright(v)) preorderpositions(right(v), pos); // recurse on right child public Iterable<Position<E>> positions() { PositionList<Position<E>> positions = new NodePositionList<Position<E>>(); if(size!= 0) preorderpositions(root(), positions); return positions; A.A. 16/17 DA1 - Andrea Pietracaprina 12

Classe LinkedBinaryTree public Iterable<Position<E>> children(position<e> v) throw InvalidPositionException { PositionList<Position<E>> children = new NodePositionList<Position<E>>(); if (hasleft(v)) children.addlast(left(v)); if (hasright(v)) children.addlast(right(v)); return children; public Iterator<E> iterator() { Iterable<Position<E>> positions = positions(); PositionList<E> elements = new NodePositionList<E>(); for (Position<E> pos: positions) elements.addlast(pos.element()); return elements.iterator(); N.B. In ogni iterazione del ciclo for nel metodo iterator(), alla variabile pos viene assegnato il prossimo oggetto dell iteratore fornito da positions.iterator(), ovvero la prossima position (vedi lucidi seguenti) A.A. 16/17 DA1 - Andrea Pietracaprina 13

Statement for-each for (Position<E> pos: positions) elements.addlast(pos.element()); equivale a for (Iterator<Position<E>> it = positions.iterator(); it.hasnext(); ) { Position<E> pos = it.next(); elements.addlast(pos.element()); A.A. 16/17 DA1 - Andrea Pietracaprina 14