# Object Oriented Software Design

Save this PDF as:

Size: px
Start display at page:

## Transcription

1 Object Oriented Software Design Inner classes, RTTI, Tree implementation Giuseppe Lipari Scuola Superiore Sant Anna Pisa October 29, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

2 Outline 1 Run-Time Type Identification 2 Anonymous inner classes 3 Binary Trees G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

3 Outline 1 Run-Time Type Identification 2 Anonymous inner classes 3 Binary Trees G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

4 The shape example Consider a hierarchy of Shape classes Shape area() Triangle Rectangle Circle diagonal() The Shape class is abstract, it has an abstract method to compute the area of the shape. Now suppose we have an array of Shapes, and we would like to compute the area for all of them. G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

5 Shapes This is the base class oosd/shapes/shape.java package oosd.shapes; public abstract class Shape { protected String name; public Shape(String s) { name = s; public abstract double area(); G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

6 Triangle And one derived class: oosd/shapes/triangle.java package oosd.shapes; public class Triangle extends Shape { private double base = 0, height = 0; public Triangle() { this("triangle"); public Triangle(String s) { super(s); public Triangle(String s, double b, double h) { this(s); base = b; height = h; public double area() { System.out.println("Computing the area of Triangle " + name); return base * height / 2; G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

7 A list of Shapes Let s use the QueueListIt class we have seen last lecture QueueListIt<Shape> myq = new QueueListIt<Shape>(); // upcast, never fails myq.push(new Circle("red", 5.0)); myq.push(new Triangle("yellow", 3.0, 4.0)); myq.push(new Rectangle("blue", 3.0, 4.0)); for (Shape s : myq) System.out.println(s.area()); Everything as expected G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

8 A new method Rectangle derives from Shape, and adds a new method diagonal() to compute the diagonal oosd/shapes/rectangle.java public class Rectangle extends Shape { private double base = 0, height = 0; public Rectangle(String s) { super(s); public Rectangle() { this("rectangle"); public Rectangle(String s, double b, double h) { this(s); height = h; base = b; public double area() { System.out.println("Computing the area of Rectangle " + name); return base * height; public double diagonal() { System.out.println("Computing the diagonal"); return Math.sqrt(base*base+height*height); G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

9 How to call diagonal? We would like to call diagonal only for Rectangles because it does not make sense to call diagonal for Circles and Triangles But, we have a problem: for (Shape s : myq) { System.out.println(s.area()); System.out.println(s.diagonal()); Compilation error: diagonal() is not part of the interface of Shape G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

10 Downcast We could force s to become a reference to Rectangle, so that diagonal() is in the interface now. for (Shape s : myq) { System.out.println(s.area()); System.out.println(((Rectangle)s).diagonal()); This is called downcast, and must be explicit, because a Shape is not (always) a rectangle Downcast is not safe Unfortunately, if s is pointing to a Triangle, Java run-time raises an exception ClassCastException G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

11 Solution 1: catch the exception By catching the exception, everything works fine ClientExc.java import java.util.*; import oosd.shapes.*; import oosd.containers.*; class ClientExc { public static void main(string args[]) { QueueListIt<Shape> myq = new QueueListIt<Shape>(); myq.push(new Circle("red", 5.0)); myq.push(new Triangle("yellow", 3.0, 4.0)); myq.push(new Rectangle("blue", 3.0, 4.0)); for (Shape s: myq) { System.out.println(s.area()); try { double d = ((Rectangle)s).diagonal(); System.out.println(d); catch(classcastexception e) { System.out.println("Not a rectangle"); G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

12 Upcasting and downcasting When we insert in the QueueListIt class, the perform an upcast Upcast is always safe. To understand if there is a Rectangle, we perform a downcast. Downcast is not safe at all (raises an exception), and it should be avoided when necessary. to perform downcast Java has to identify the actual object type and see if the cast can be performed. G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

13 instanceof To avoid the exception (which is clumsy and inefficient), you can use the keyword instanceof ClientRTTI.java import oosd.containers.*; class ClientRTTI { public static void main(string args[]) { QueueListIt<Shape> myq = new QueueListIt<Shape>(); myq.push(new Circle("red", 5.0)); myq.push(new Triangle("yellow", 3.0, 4.0)); myq.push(new Rectangle("blue", 3.0, 4.0)); Iterator<Shape> it = myq.iterator(); while (it.hasnext()) { Shape s = it.next(); System.out.println(s.area()); if (s instanceof Rectangle) System.out.println(((Rectangle)s).diagonal()); instanceof works well with inheritance G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

14 The Class object All information on a specific class are contained in a special object of type Class. The class Class contains a certain number of methods to analyse the interface: forname(string s) returns a Class Object given the class name isinstance(object o) returns true if the specified object is an instance of the class An example in the next slide G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

15 The usage of Class ClientRTTI2.java class ClientRTTI2 { public static void main(string args[]) { QueueListIt<Shape> myq = new QueueListIt<Shape>(); // upcast, never fails myq.push(new Circle("red", 5.0)); myq.push(new Triangle("yellow", 3.0, 4.0)); myq.push(new Rectangle("blue", 3.0, 4.0)); Iterator<Shape> it = myq.iterator(); while (it.hasnext()) { Shape s = it.next(); System.out.println("Object of class: " + s.getclass().getname( " in package: " + s.getclass().getpackage() System.out.println("Object is compatible with Rectangle: " + Rectangle.class.isInstance(s)); // Rectangle.class is equivalent to // Class.forName("Rectangle").isInstance(s) System.out.println(s.area()); G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

16 Downcasting? In the previous example, there was another option: put diagonal() in the interface of the base class Shape The diagonal() function in the Shape class needs to be a void function, that could also raise an exception (for example OperationNotImplemented) This approach may generate fat interfaces In this case, we chose to follow the other option However, the downcast option is not always the best one, it depends on the context This has nothing to do with the specific Java Language: it is a design problem, not a coding problem We will come back to the problem of downcasting when studying the Liskov s substitution principle. G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

17 Outline 1 Run-Time Type Identification 2 Anonymous inner classes 3 Binary Trees G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

18 Inner classes Let s have a closer look again at the QueueListIt<E>:./examples/10.java-examples/oosd/containers/QueueLi The QLIterator class is a private inner class of QueueListIt The reason for making it private is that QLIterator is an implementation of the more general notion of Iterator A different implementation is fine, as long as it conforms with the interface The user does not need to know the implementation, only the interface (i.e. how to use it) The user will never directly create a QLIterator object: it asks the container class to do the creation for him. Advantages: We can change the internal implementation without informing the user, that can continue to use its code without modifications We have achieved perfect modularity G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

19 Anonymous inner classes Sometimes, interfaces are so simple that creating a private inner class with its own name seems too much; Java provides a way do define classes on the fly interface MyInterface { int myfun(); class MyClass {... MyInterface get() { return new MyInterface() { public int myfun() {... ; A simple interface An anonymous class Notice the special syntax: new followed by the name of the interface, followed by the implementation The class has no name, so you cannot define a constructor G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

20 Anonymous iterator oosd/containers/queuelistitan.java public Iterator<E> iterator() { return new Iterator<E>() { private Node curr = head; private Node prev = null; public boolean hasnext() { if (curr == null) return false; else return true; public E next() { if (curr == null) return null; E elem = curr.elem; prev = curr; curr = curr.next; return elem; public void remove() { if (prev == null) return; // remove element Node p = prev.prev; Node f = prev.next; if (p == null) head = f; else p.next = f; if (f == null) tail = p; else f.prev = p; prev = null; ; G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

21 Anonymous classes It is surely shorter: However, in certain cases it can become cumbersome and confusing, especially when there is too much code to write If there is too much code to write (as in our example), I prefer to write a regular inner class I recommend to minimise the use of anonymous classes However, it is important to understand what do they mean when you meet them in somebody else code G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

22 Outline 1 Run-Time Type Identification 2 Anonymous inner classes 3 Binary Trees G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

23 Binary trees We will need a binary tree to organise the data for the assignment Before we look into trees, however, let s have a look at another common container, which is widely used in many applications: the Stack The stack may be useful for storing partial results For example, when we have to multiply the results of two sub-expressions, we must first compute the sub-expressions; The partial results may be stored into a stack, and retrieved when needed Example: (3+2) (6 4) Compute 3+2, and put the result 5 on the stack Compute 6 4 and put the result on the stack Extract the last two results from the stack, and multiply them G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

24 Stack A stack is a very simple data structure. A stack can hold a set of uniform data, like an array (for example, integers) Data is ordered according to the LIFO (Last-In-First-Out) strategy Two main operations are defined on the data structure: Push: a new data in inserted in the top of the stack Pop: data is extracted from the top stack Usually, we can also read the element at the top of the stack with a peek operation G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

25 Stack usage In the following program, we use the standard Java implementation of Stack StackDemo.java import java.util.*; class StackDemo { public static void main(string args[]) { Stack<Integer> mystack = new Stack<Integer>(); for (int i=0; i<10; i++) mystack.push(new Integer(i)); while (!mystack.empty()) System.out.print(" " + mystack.pop()); System.out.println(""); G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

26 Tree A tree is a data structure defined as follows: A tree may contain one or more nodes A node in a tree represents an element containing data. A node may have zero or more child nodes. The children nodes are called also descendants. Each node may have a parent node A tree consists of one root node, plus zero or more children sub-trees G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

27 Example A is the root of the tree B is root of one sub tree of A A B E I C H F G L D M N G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

28 Binary trees In a binary tree, a node can have at most 2 children Left and right A leaf node is a node without children A root node is a node without parents There is only one root node Each node in the tree is itself a sub-tree A leaf node is a sub-tree with one single node G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

29 How to implement a tree One basic data structure is the Node, as in the List data structure In the List structure, a Node had two links, next and prev (see./examples/10.java-examples/oosd/containers/queuelis A possible implementation for a Tree Node is the following: class Node<E> { E elem; Node left; Node right; Optionally, it could contain a link to the parent node If one of the links is equal to null then the corresponding sub-tree is null G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

30 Interface for a Tree We must be able to: Create single-node trees Link a sub-tree to single-node tree (to the left or to the right) Get the left (right) sub-tree Also, we would like to print the contents of the tree To do this, we need to establish an order of printing G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

31 Visiting a tree There are two ways of listing the contents of a tree Depth-first Pre-order: first the root node is visited, then the left sub-tree, then the right sub-tree Post-order: first the left sub-tree is visited, then the right sub-tree, then the root node In-order: first the left sub-tree is visited, then the root node, then the right sub-tree Breadth first First the root node is visited; then all the children; then all the children of the children; and so on G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

32 Example A Breadth first: A B E C D F G B E Pre-order: A B C D E F G Post-order: C D B E F G E A C D F G In-order: C B D A F E G G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

33 Implementation of a Binary Tree BTree.java Let s start with the node public class BTree<E> { private class Node { E elem; Node l; Node r; void addleft(node n) { l = n; void addright(node n) { r = n; Node(E elem) { this.elem = elem; private Node root = null; private BTree(Node n) { root = n; G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

34 Adding nodes BTree.java public BTree(E elem) { root = new Node(elem); public BTree<E> addleft(btree<e> t) { root.addleft(t.root); return this; public BTree<E> addright(btree<e> t) { root.addright(t.root); return this; public BTree<E> linktoleft(btree<e> t) { t.root.addleft(root); return this; public BTree<E> linktoright(btree t) { t.root.addright(root); return this; G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

35 BTree continued BTree.java public BTree<E> getleftsubtree() { if (root == null) return null; else return new BTree(root.l); public BTree<E> getrightsubtree() { if (root == null) return null; else return new BTree(root.r); void printpostorder() { if (root == null) return; else { getleftsubtree().printpostorder(); getrightsubtree().printpostorder(); System.out.print(root.elem); System.out.print(" "); G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

36 BTree continued BTree.java void printpreorder() { if (root == null) return; else { System.out.print(root.elem); System.out.print(" "); getleftsubtree().printpreorder(); getrightsubtree().printpreorder(); void printinorder() { if (root == null) return; else { getleftsubtree().printinorder(); System.out.print(root.elem); System.out.print(" "); getrightsubtree().printinorder(); G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

37 BTree usage BTree.java public static void main(string args[]) { BTree<String> mytree = new BTree<String>("*"); BTree<String> ll = new BTree<String>("+"); BTree<String> rr = new BTree<String>("-"); rr.addleft(new BTree<String>("2")). addright(new BTree<String>("3")). linktoleft(mytree); ll.addleft(new BTree<String>("6")). addright(new BTree<String>("4")). linktoright(mytree); System.out.println("Post Order: "); mytree.printpostorder(); System.out.println("\nPre Order: "); mytree.printpreorder(); System.out.println("\nIn Order: "); mytree.printinorder(); System.out.println("\n"); G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

38 A tree Iterator In reality, we would like to make the visiting operation more abstract In fact, while visiting we may want to perform other operations than printing For example, evaluating and expression (!) Therefore, we need to generalise the algorithm for visiting the tree, and make it independent of the specific operation To do so, we have to modify the structure of the algorithm In the previous program, we have used a simple recursive algorithm Now we need to implement an iterative algorithm, through an iterator The implementation is slightly complex, so pay attention! G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

39 The node BTreeIt.java public class BTreeIt<E> { private class Node { E elem; Node l; Node r; Node p; void addleft(node n) { l = n; n.p = this; void addright(node n) { r = n; n.p = this; Node(E elem) { this.elem = elem; We now use also the parent link p, because we will need to go up in the hierarchy G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

40 Iterator BTreeIt.java private class PostOrderIterator implements Iterator<E> { Node next; Node last; PostOrderIterator() { next = root; last = null; movetoleftmostleaf(); private void movetoleftmostleaf() { do { // go down left while (next.l!= null) next = next.l; // maybe there is a node with no left but some right... // then go down rigth if (next.r!= null) next = next.r; while (next.l!= null next.r!= null); // exit when both left and right are null G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

41 The next method BTreeIt.java public E next() throws NoSuchElementException { if (next == null) throw new NoSuchElementException(); E key = next.elem; // I already visited left and right, // so I have to go up (and maybe right) last = next; next = next.p; if (next!= null && last == next.l) { next = next.r; movetoleftmostleaf(); return key; /* */ /* INTERFACE */ /* */ public BTreeIt(E elem) { root = new Node(elem); public BTreeIt<E> addleft(btreeit<e> t) { root.addleft(t.root); G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

42 The tree class Just the same, except for the method to return the iterator: Iterator<E> postorderiterator() { return new PostOrderIterator(); Notice that we do not need the printxxx() functions, because we can use the iterator G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

43 BTreeIt usage BTreeIt.java addright(new BTreeIt<String>("*"). addleft(new BTreeIt<String>("2")). addright(new BTreeIt<String>("2")) ). linktoright(mytree); System.out.println("Post Order: "); Iterator<String> it = mytree.postorderiterator(); while (it.hasnext()) System.out.println(it.next()); G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

44 Exercises Write the pre-order and the in-order iterators for class BTreeIt G. Lipari (Scuola Superiore Sant Anna) Introduction to Java October 29, / 44

### Ordered Lists and Binary Trees

Data Structures and Algorithms Ordered Lists and Binary Trees Chris Brooks Department of Computer Science University of San Francisco Department of Computer Science University of San Francisco p.1/62 6-0:

### SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

SE 360 Advances in Software Development Object Oriented Development in Java Polymorphism Dr. Senem Kumova Metin Modified lecture notes of Dr. Hüseyin Akcan Inheritance Object oriented programming languages

### Binary Search Trees (BST)

Binary Search Trees (BST) 1. Hierarchical data structure with a single reference to node 2. Each node has at most two child nodes (a left and a right child) 3. Nodes are organized by the Binary Search

### Data Structures and Algorithms

Data Structures and Algorithms CS245-2016S-06 Binary Search Trees David Galles Department of Computer Science University of San Francisco 06-0: Ordered List ADT Operations: Insert an element in the list

### UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming 1 2 Foreword First of all, this book isn t really for dummies. I wrote it for myself and other kids who are on the team. Everything

Inheritance, overloading and overriding Recall with inheritance the behavior and data associated with the child classes are always an extension of the behavior and data associated with the parent class

### Object Oriented Software Design - I

Object Oriented Software Design - I Object Oriented Design Principles Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 28, 2011 G. Lipari (Scuola Superiore Sant Anna)

### Trees LOGO STYLE GUIDE Schools within the University 1 19

Trees 1 Example Tree 2 A Generic Tree 3 Tree ADT n Tree definition q A tree is a set of nodes which may be empty q If not empty, then there is a distinguished node r, called root and zero or more non-empty

### CMSC 206. Binary Search Trees

CMSC 206 Binary Search Trees 1 Binary Search Tree n A Binary Search Tree is a Binary Tree in which, at every node v, the values stored in the left subtree of v are less than the value at v and the values

### CMSC 341. Binary Search Trees. Textbook section: 4.3

CMSC 341 Binary Search Trees Textbook section: 4.3 Binary Search Tree A Binary Search Tree is a Binary Tree in which, at every node v, the values stored in the left subtree of v are less than the value

### API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.

Sequences and Urns 2.7 Lists and Iterators Sequence. Ordered collection of items. Key operations. Insert an item, iterate over the items. Design challenge. Support iteration by client, without revealing

### Object Oriented Software Design

Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 28, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction

### 1.204 Lecture 6. Data structures: stacks, queues, trees, dictionaries. Data structures

1.204 Lecture 6 Data structures: stacks, queues, trees, dictionaries Data structures Correct and efficient representation of data and applicable rules Stack: last in, first out discipline Queue: first

### CE204 Data Structures and Algorithms Part 3

CE204 Data Structures and Algorithms Part 3 23/01/2016 CE204 Part 3 1 Trees The ADTs encountered so far have been linear; list and array implementations have been adequate. We now consider a nonlinear

### A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Binary Search Trees 1 The general binary tree shown in the previous chapter is not terribly useful in practice. The chief use of binary trees is for providing rapid access to data (indexing, if you will)

Graduate Assessment Test (Sample) CS201-203 1. Fibonacci sequence is defined by a recurrence relation. The series is: 0,1,1,2,3,5,8,13,... Write a complete recursive method/function that returns the fibonacci

### Object Oriented Software Design

Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 14, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction

### Java Interview Questions and Answers

1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java

### Object Oriented Software Design

Object Oriented Software Design Polymorphism, Abstract Classes, Interfaces Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 3, 2011 G. Lipari (Scuola Superiore Sant

### Course: Programming II - Abstract Data Types. The ADT Binary Tree

The ADT Binary Tree The Binary Tree is a more general ADT than the linear list: it allows one item to have two immediate successors. Definition The ADT Binary Tree is a finite set of nodes which is either

### RECURSIVE BST OPERATIONS. with more Java generics

RECURSIVE BST OPERATIONS with more Java generics 1 Let s implement a BST class, avoiding iteration. This will give us more practice with trees, and with recursion. It will also give us a chance for a continued

### D06 PROGRAMMING with JAVA

Cicles Formatius de Grau Superior Desenvolupament d Aplicacions Informàtiques D06 PROGRAMMING with JAVA Ch20 Data Structures I PowerPoint presentation, created by Angel A. Juan - ajuanp(@)gmail.com, for

### Stacks, Queues & Trees. The Stack Interface. The Stack Interface. Prof. Dr. Harald Gall. Institut für Informatik Universität Zürich

Stacks, Queues & Trees Prof. Dr. Harald Gall Institut für Informatik Universität Zürich http://seal.ifi.uzh.ch The Stack Interface!! Stack!! Data structure holding several items.!! New items added to the

### Data Structure with C

Subject: Data Structure with C Topic : Tree Tree A tree is a set of nodes that either:is empty or has a designated node, called the root, from which hierarchically descend zero or more subtrees, which

### Data Structures and Algorithms Binary Search Trees

Data Structures and Algorithms Binary Search Trees Chris Brooks Department of Computer Science University of San Francisco Department of Computer Science University of San Francisco p.1/34 To find the

### Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

Trees Chapter 23 Motivation Tree is a fundamental data-structure Operating Systems: Directory Structure Artificial Intelligence: Game Playing Programs Programming Languages: Inheritance Data Structure:

### Class 28: Binary Search Trees. Binary Search Trees

Introduction to Computation and Problem Solving Class 2: Binary Search Trees Prof. Steven R. Lerman and Dr. V. Judson Harward Binary Search Trees In the previous lecture, we defined the concept of binary

### First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science

First Java Programs V. Paúl Pauca Department of Computer Science Wake Forest University CSC 111D Fall, 2015 Hello World revisited / 8/23/15 The f i r s t o b l i g a t o r y Java program @author Paul Pauca

### MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push) -----------------------------------------

=============================================================================================================================== DATA STRUCTURE PSEUDO-CODE EXAMPLES (c) Mubashir N. Mir - www.mubashirnabi.com

### Object Oriented Software Design II

Object Oriented Software Design II Introduction to C++ Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 20, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February

### Java Programming Language

Lecture 1 Part II Java Programming Language Additional Features and Constructs Topics in Quantitative Finance: Numerical Solutions of Partial Differential Equations Instructor: Iraj Kani Subclasses and

### ECE 250 Data Structures and Algorithms MIDTERM EXAMINATION 2008-10-23/5:15-6:45 REC-200, EVI-350, RCH-106, HH-139

ECE 250 Data Structures and Algorithms MIDTERM EXAMINATION 2008-10-23/5:15-6:45 REC-200, EVI-350, RCH-106, HH-139 Instructions: No aides. Turn off all electronic media and store them under your desk. If

### CS 111 Classes I 1. Software Organization View to this point:

CS 111 Classes I 1 Software Organization View to this point: Data Objects and primitive types Primitive types operators (+, /,,*, %). int, float, double, char, boolean Memory location holds the data Objects

### root node level: internal node edge leaf node CS@VT Data Structures & Algorithms 2000-2009 McQuain

inary Trees 1 A binary tree is either empty, or it consists of a node called the root together with two binary trees called the left subtree and the right subtree of the root, which are disjoint from each

### Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

Definition Course: Programming II - Abstract Data Types The ADT Stack The ADT Stack is a linear sequence of an arbitrary number of items, together with access procedures. The access procedures permit insertions

### Lecture 4. The Java Collections Framework

Lecture 4. The Java s Framework Chapters 6.3-6.4-1 - Outline Introduction to the Java s Framework Iterators Interfaces Classes Classes - 2 - The Java s Framework We will consider the Java s Framework as

### Collections & Data Structures. CS 3: Computer Programming in Java

Collections & Data Structures CS 3: Computer Programming in Java Objectives The concept of a collection Separating the interface from the implementation Dynamic data structures Linked lists Queues and

### The ADT Binary Search Tree. Recursive Tree Traversals. The ADT Binary Search Tree. The ADT Binary Search Tree. In-order

Recursive Tree Traversals The ADT Binary Search Tree In-order private void printinorder(treenode node) { if (node!= null) { printinorder(node.getleft()); System.out.print(node.getItem() + " "); printinorder(node.getright());

### CSE 143 Lecture 20. Binary Search Trees. read slides created by Marty Stepp

CSE 143 Lecture 20 Binary Search Trees read 17.3 slides created by Marty Stepp http://www.cs.washington.edu/143/ Binary search trees binary search tree ("BST"): a binary tree that is either: empty (null),

### Definition. E.g. : Attempting to represent a transport link data with a tree structure:

The ADT Graph Recall the ADT binary tree: a tree structure used mainly to represent 1 to 2 relations, i.e. each item has at most two immediate successors. Limitations of tree structures: an item in a tree

### 1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Answer the following 1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++ 2) Which data structure is needed to convert infix notations to postfix notations? Stack 3) The

### Data Structures Using Java

Data Structures Using Java D. S. Malik P. S. Nair THOMSON COURSE TECHNOLOGY Australia Canada Mexico Singapore Spain United Kingdom United States TABLE OF Contents PREFACE XXV 1.Software Engineering Principles

### Algorithms and Data Structures Written Exam Proposed SOLUTION

Algorithms and Data Structures Written Exam Proposed SOLUTION 2005-01-07 from 09:00 to 13:00 Allowed tools: A standard calculator. Grading criteria: You can get at most 30 points. For an E, 15 points are

### Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types

Interfaces & Java Types Lecture 10 CS211 Fall 2005 Java Interfaces So far, we have mostly talked about interfaces informally, in the English sense of the word An interface describes how a client interacts

### Overview of Data Structures

UNIT 3 Concrete Data Types Classification of Data Structures Concrete vs. Abstract Data Structures Most Important Concrete Data Structures Arrays Records Linked Lists Binary Trees Overview of Data Structures

### Software Engineering Techniques

Software Engineering Techniques Low level design issues for programming-in-the-large. Software Quality Design by contract Pre- and post conditions Class invariants Ten do Ten do nots Another type of summary

### 6 Data Structures. 6.1 Quadtree. 6.2 Binary search tree

6 Data Structures 6.1 Quadtree he basic principles of quadtrees have been outlined in the lecture. ollow these steps for the implementation in Java: 1. Download the quadtree.zip file from the course web

### Topic 15. The Binary Search Tree ADT

Topic 15 The Binary Search Tree ADT Binary Search Tree A binary search tree (BST) is a binary tree with an ordering property of its elements, such that the data in any internal node is Greater than the

### Lecture 4. The Java Collections Framework

Lecture 4. The Java s Framework Chapters 6.3-6.4-1 - The Java s Framework We will consider the Java s Framework as a good example of how apply the principles of objectoriented software engineering (see

### School of Informatics, University of Edinburgh Computer Science 1 Ah [03 04]

School of Informatics, University of Edinburgh Computer Science 1 Ah [03 04] CS1Ah Lecture Note 25 Binary Search Trees This lecture studies binary trees in more detail, in particular their application

### Module 7. Polymorphism, Abstract Classes, and Interfaces. Adapted from Absolute Java, Rose Williams, Binghamton University

Module 7 Polymorphism, Abstract Classes, and Interfaces Adapted from Absolute Java, Rose Williams, Binghamton University Introduction to Polymorphism There are three main programming mechanisms that constitute

### Intro to Trees. or, doing even better than linear time

Intro to Trees or, doing even better than linear time Linked Lists Are Linear Access Time Usually pretty good. But consider terabytes of data, like from daily satellite images. 2 40 (or ~10 12) 1,099,511,627,776

### Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Masters programmes in Computer Science and Information Systems Object-Oriented Design and Programming Sample module entry test xxth December 2013 This sample paper has more questions than the real paper

### COMP1008 Inheritance. Outline. Subclass and Superclass. Inheritance. Multiple Subclasses. Inheritance Hierarchy

Outline COMP1008 Inheritance Introduction to inheritance. How Java supports inheritance. Inheritance is a key feature of object-oriented programming. 2 Inheritance Subclass and Superclass Models the kind-of

### Binary Trees and Huffman Encoding Binary Search Trees

Binary Trees and Huffman Encoding Binary Search Trees Computer Science E119 Harvard Extension School Fall 2012 David G. Sullivan, Ph.D. Motivation: Maintaining a Sorted Collection of Data A data dictionary

### Master of Sciences in Informatics Engineering Programming Paradigms 2005/2006. Final Examination. January 24 th, 2006

Master of Sciences in Informatics Engineering Programming Paradigms 2005/2006 Final Examination January 24 th, 2006 NAME: Please read all instructions carefully before start answering. The exam will be

### Questions 1 through 25 are worth 2 points each. Choose one best answer for each.

Questions 1 through 25 are worth 2 points each. Choose one best answer for each. 1. For the singly linked list implementation of the queue, where are the enqueues and dequeues performed? c a. Enqueue in

### LAB4 Making Classes and Objects

LAB4 Making Classes and Objects Objective The main objective of this lab is class creation, how its constructer creation, object creation and instantiation of objects. We will use the definition pane to

### Summary. Pre requisition. Content Details: 1. Basics in C++

Summary C++ Language is one of the approaches to provide object-oriented functionality with C like syntax. C++ adds greater typing strength, scoping and other tools useful in object-oriented programming

### Big Data and Scripting. Part 4: Memory Hierarchies

1, Big Data and Scripting Part 4: Memory Hierarchies 2, Model and Definitions memory size: M machine words total storage (on disk) of N elements (N is very large) disk size unlimited (for our considerations)

### Reading a Text File. Reading and Writing Text Files Exceptions. Testing for more input. Example: Count Words

Reading a Text File Reading and Writing Text Files Exceptions 15-121 Fall 2010 Margaret Reid-Miller A Scanner object can be connected to many input sources: keyboard, file, network, string To read a text

### Trees & Binary Search Trees

CMSC 132: Object-Oriented Programming II Trees & Binary Search Trees Department of Computer Science University of Maryland, College Park Trees Trees are hierarchical data structures One-to-many relationship

### Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Translation Translating to Java Introduction to Computer Programming The job of a programmer is to translate a problem description into a computer language. You need to be able to convert a problem description

### AP Computer Science Java Subset

APPENDIX A AP Computer Science Java Subset The AP Java subset is intended to outline the features of Java that may appear on the AP Computer Science A Exam. The AP Java subset is NOT intended as an overall

### 1.00 Lecture 35. Data Structures: Introduction Stacks, Queues. Reading for next time: Big Java: 15.1-15.3. Data Structures

1.00 Lecture 35 Data Structures: Introduction Stacks, Queues Reading for next time: Big Java: 15.1-15.3 Data Structures Set of reusable classes used in algorithms, simulations, operating systems, applications

### Binary Search Trees. Yes! So, a binary tree T is a binary search tree if T is a single node.

Which are Binary Search Trees (BST)? Binary Search Trees So, a binary tree T is a binary search tree if T is a single node. Yes! No! All the values on the left subtree must be less than the value at the

### Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007 The Java Type System By now, you have seen a fair amount of Java. Time to study in more depth the foundations of the language,

### Algorithms and Data Structures

Algorithms and Data Structures Part 2: Data Structures PD Dr. rer. nat. habil. Ralf-Peter Mundani Computation in Engineering (CiE) Summer Term 2016 Overview general linked lists stacks queues trees 2 2

### Intro to Programming in Java Practice Midterm

600.107 Intro to Programming in Java Practice Midterm This test is closed book/notes. SHORT ANSWER SECTION [18 points total] 1) TRUE/FALSE - Please circle your choice: Tr for true, Fa for false. [1 point

### Announcements. CSE332: Data Abstractions. Lecture 9: B Trees. Today. Our goal. M-ary Search Tree. M-ary Search Tree. Ruth Anderson Winter 2011

Announcements CSE2: Data Abstractions Project 2 posted! Partner selection due by 11pm Tues 1/25 at the latest. Homework due Friday Jan 28 st at the BEGINNING of lecture Lecture 9: B Trees Ruth Anderson

### 12 Abstract Data Types

12 Abstract Data Types 12.1 Source: Foundations of Computer Science Cengage Learning Objectives After studying this chapter, the student should be able to: Define the concept of an abstract data type (ADT).

### Data Structures. Topic #4

Topic #4 Today s Agenda Stack and Queue ADTs What are they Like Ordered Lists, are position oriented Use of Data Structures for Stacks and Queues arrays (statically & dynamically allocated) linear linked

### Previous Lectures. B-Trees. External storage. Two types of memory. B-trees. Main principles

B-Trees Algorithms and data structures for external memory as opposed to the main memory B-Trees Previous Lectures Height balanced binary search trees: AVL trees, red-black trees. Multiway search trees:

### Binary Heaps * * * * * * * / / \ / \ / \ / \ / \ * * * * * * * * * * * / / \ / \ / / \ / \ * * * * * * * * * *

Binary Heaps A binary heap is another data structure. It implements a priority queue. Priority Queue has the following operations: isempty add (with priority) remove (highest priority) peek (at highest

### A TOOL FOR DATA STRUCTURE VISUALIZATION AND USER-DEFINED ALGORITHM ANIMATION

A TOOL FOR DATA STRUCTURE VISUALIZATION AND USER-DEFINED ALGORITHM ANIMATION Tao Chen 1, Tarek Sobh 2 Abstract -- In this paper, a software application that features the visualization of commonly used

### Announcements. FINAL EXAM Monday May 21, 1:30pm Review Session. Wednesday May 16, 7-9pm

Announcements FINAL EXAM Monday May 21, 1:30pm Review Session Wednesday May 16, 7-9pm 1 Recitation 12 Root Finding, Sorting, Stacks, Queues 2 Outline Linked Lists Sorting Queues 3 Object References Let

### Home Page. Data Structures. Title Page. Page 1 of 24. Go Back. Full Screen. Close. Quit

Data Structures Page 1 of 24 A.1. Arrays (Vectors) n-element vector start address + ielementsize 0 +1 +2 +3 +4... +n-1 start address continuous memory block static, if size is known at compile time dynamic,

### UNIVERSITI MALAYSIA SARAWAK KOTA SAMARAHAN SARAWAK PSD2023 ALGORITHM & DATA STRUCTURE

STUDENT IDENTIFICATION NO UNIVERSITI MALAYSIA SARAWAK 94300 KOTA SAMARAHAN SARAWAK FAKULTI SAINS KOMPUTER & TEKNOLOGI MAKLUMAT (Faculty of Computer Science & Information Technology) Diploma in Multimedia

### Introduction to Programming

Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems sjmaybank@dcs.bbk.ac.uk Spring 2015 Week 2b: Review of Week 1, Variables 16 January 2015 Birkbeck

### Lab Manual. CPCS204 Data Structures 1. Lab H

Lab Manual CPCS204 Data Structures 1 1438H Lab - 8 Learning Procedure 1) Stage J (Journey inside-out the concept) 2) Stage a 1 (apply the learned) 3) Stage v (verify the accuracy) 4) Stage a 2 (assess

### Introduction to Java A First Look

Introduction to Java A First Look Java is a second or third generation object language Integrates many of best features Smalltalk C++ Like Smalltalk Everything is an object Interpreted or just in time

### Structural Design Patterns Used in Data Structures Implementation

Structural Design Patterns Used in Data Structures Implementation Niculescu Virginia Department of Computer Science Babeş-Bolyai University, Cluj-Napoca email address: vniculescu@cs.ubbcluj.ro November,

### 243 Week 3 Lecture - Interfaces

One problem, many solutions 243 Week 3 Lecture - Interfaces Suppose we want to implement a set of classes to represent various shapes such as circles and rectangles. We want to be able to calculate the

### Topic Java Class. Library INTRODUCTION LEARNING OUTCOMES. By the end of this topic, you should be able to:

Topic Java Class Library 8 LEARNING OUTCOMES By the end of this topic, you should be able to: 1. Describe the meaning of package in Java; 2. Describe the purpose of keyword import; 3. Describe of how classes

### Converting a Number from Decimal to Binary

Converting a Number from Decimal to Binary Convert nonnegative integer in decimal format (base 10) into equivalent binary number (base 2) Rightmost bit of x Remainder of x after division by two Recursive

### Chapter 2 Introduction to Java programming

Chapter 2 Introduction to Java programming 1 Keywords boolean if interface class true char else package volatile false byte final switch while throws float private case return native void protected break

### CompuScholar, Inc. Alignment to Utah's Computer Programming II Standards

CompuScholar, Inc. Alignment to Utah's Computer Programming II Standards Course Title: TeenCoder: Java Programming Course ISBN: 978 0 9887070 2 3 Course Year: 2015 Note: Citation(s) listed may represent

### Chapter 12. Support for. Oi t Programming

Chapter 12 Support for Object-Oriented Oi t Programming Chapter 12 Topics Introduction Object-Oriented Programming Design Issues for Object-Oriented Languages Support for Object-Oriented Programming g

### 1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

1.00 Lecture 1 Course Overview Introduction to Java Reading for next time: Big Java: 1.1-1.7 Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

### Lecture J - Exceptions

Lecture J - Exceptions Slide 1 of 107. Exceptions in Java Java uses the notion of exception for 3 related (but different) purposes: Errors: an internal Java implementation error was discovered E.g: out

### 1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Programming Concepts Practice Test 1 1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius 2) Consider the following statement: System.out.println("1

### Java CPD (I) Frans Coenen Department of Computer Science

Java CPD (I) Frans Coenen Department of Computer Science Content Session 1, 12:45-14:30 (First Java Programme, Inheritance, Arithmetic) Session 2, 14:45-16:45 (Input and Programme Constructs) Materials

### Object Oriented Software Design II

Object Oriented Software Design II C++ intro Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 26, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26,

### // Basic node stored in unbalanced binary search trees // Note that this class is not accessible outside // of this package.

// Basic node stored in unbalanced binary search trees // Note that this class is not accessible outside // of this package. class BinaryNode AnyType element; // The data in the node BinaryNode

### INTERNATIONAL JOURNAL OF PURE AND APPLIED RESEARCH IN ENGINEERING AND TECHNOLOGY

INTERNATIONAL JOURNAL OF PURE AND APPLIED RESEARCH IN ENGINEERING AND TECHNOLOGY A PATH FOR HORIZING YOUR INNOVATIVE WORK A REVIEW ON THE USAGE OF OLD AND NEW DATA STRUCTURE ARRAYS, LINKED LIST, STACK,

### The Interface Concept

Multiple inheritance Interfaces Four often used Java interfaces Iterator Cloneable Serializable Comparable The Interface Concept OOP: The Interface Concept 1 Multiple Inheritance, Example Person name()

### Lesson 52.. Binary Search Tree

Lesson 52.. Binary Search Tree 52-1 We will begin by showing how a binary search tree is constructed. We will construct our tree from the following sequence of integers;, 56, 52, 25, 74, and 54. Each number