CompSci 100e 7.1 Plan for the week l Review:  Boggle  Coding standards and inheritance l Understand linked lists from the bottom up and top-down  As.

Slides:



Advertisements
Similar presentations
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Advertisements

Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
1 Trees Tree nomenclature Implementation strategies Traversals –Depth-first –Breadth-first Implementing binary trees Reading: L&C 9.1 – 9.7.
Fall 2007CS 2251 Trees Chapter 8. Fall 2007CS 2252 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information.
Chapter 12 C Data Structures Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Chapter 12 Trees. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Define trees as data structures Define the terms.
Data Structures Using C++ 2E Chapter 11 Binary Trees and B-Trees.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 20: Binary Trees.
CPS 100, Spring From data to information to knowledge l Data that’s organized can be processed  Is this a requirement?  What does “organized”
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Comp 249 Programming Methodology Chapter 15 Linked Data Structure - Part B Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Chapter Tow Search Trees BY HUSSEIN SALIM QASIM WESAM HRBI FADHEEL CS 6310 ADVANCE DATA STRUCTURE AND ALGORITHM DR. ELISE DE DONCKER 1.
FEN 2012UCN Technology - Computer Science 1 Data Structures and Collections Principles revisited.NET: –Two libraries: System.Collections System.Collections.Generics.
CS2110: SW Development Methods Textbook readings: MSD, Chapter 8 (Sect. 8.1 and 8.2) But we won’t implement our own, so study the section on Java’s Map.
CompSci 100 Prog Design and Analysis II Sept 7, 2010 Prof. Rodger 1CompSci 100 Fall 2010.
CPS 100, Spring Conventions in Compsci 100 projects l We want you to concentrate on algorithms and data structures  Not on rendering fonts, interacting.
CPS Wordcounting, sets, and the web l How does Google store all web pages that include a reference to “peanut butter with mustard”  What efficiency.
Data Structures and Abstract Data Types "Get your data structures correct first, and the rest of the program will write itself." - David Jones.
CPS Data processing example l Scan a large (~ 10 7 bytes) file l Print the 20 most frequently used words together with counts of how often they.
CPS 100, Spring Trees: no data structure lovelier?
Searching: Binary Trees and Hash Tables CHAPTER 12 6/4/15 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,
Spring 2010CS 2251 Trees Chapter 6. Spring 2010CS 2252 Chapter Objectives Learn to use a tree to represent a hierarchical organization of information.
CPS 100, Spring From data to information l Data that’s organized can be processed  Is this a requirement?  What does “organized” means l Purpose.
CompSci 100e Program Design and Analysis II March 29, 2011 Prof. Rodger CompSci 100e, Spring20111.
Compsci 100, Fall Data and Information How and why do we organize data? Differences between data and information? What about knowledge?
Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
Data structures Abstract data types Java classes for Data structures and ADTs.
1 Chapter 17 Object-Oriented Data Structures. 2 Objectives F To describe what a data structure is (§17.1). F To explain the limitations of arrays (§17.1).
CompSci 100e 7.1 From doubly-linked lists to binary trees l Instead of using prev and next to point to a linear arrangement, use them to divide the universe.
CompSci 100e 7.1 Plan for the week l Review:  Union-Find l Understand linked lists from the bottom up and top-down  As clients of java.util.LinkedList.
CPS Scoreboard l What else might we want to do with a data structure? l What are maps’ limitations? AlgorithmInsertionDeletionSearch Unsorted.
IKI 10100I: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100I: Data.
CompSci 100e 3.1 Plan for the week l Classes and Objects l Model-View-Controller l Maps and Hashing l Upcoming  Towards Algorithm analysis l APTs:  IsomorphicWords,
CPS 100, Spring Data and Information How and why do we organize data? Differences between data and information? What about knowledge?
M180: Data Structures & Algorithms in Java Trees & Binary Trees Arab Open University 1.
Week 10 - Friday.  What did we talk about last time?  Graph representations  Adjacency matrix  Adjacency lists  Depth first search.
1 Binary Trees and Binary Search Trees Based on Dale & Co: Object-Oriented Data Structures using C++ (graphics)
Binary Search Trees (BST)
TREES K. Birman’s and G. Bebis’s Slides. Tree Overview 2  Tree: recursive data structure (similar to list)  Each cell may have zero or more successors.
Week 15 – Wednesday.  What did we talk about last time?  Review up to Exam 1.
CPS APTs and structuring data/information l Is an element in an array, Where is an element in an array?  DIY: use a loop  Use Collections, several.
1 Joe Meehean. A A B B D D I I C C E E X X A A B B D D I I C C E E X X  Terminology each circle is a node pointers are edges topmost node is the root.
BINARY TREES Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary.
Search: Binary Search Trees Dr. Yingwu Zhu. Review: Linear Search Collection of data items to be searched is organized in a list x 1, x 2, … x n – Assume.
CS Prelim Review – 10/15/09  First prelim is TOMORROW at 7:30 PM  Review session – Tonight 7:30 PM, Phillips 101  Things you should do:  Review every.
CompSci 100E 19.1 Getting in front  Suppose we want to add a new element  At the back of a string or an ArrayList or a …  At the front of a string.
CPS What's in Compsci 100? l Understanding tradeoffs: reasoning, analyzing, describing…  Algorithms  Data Structures  Programming  Design l.
Compsci 100, Fall From data to information to knowledge l Data that’s organized can be processed  Is this a requirement?  What does “organized”
18-1 Chapter 18 Binary Trees Data Structures and Design in Java © Rick Mercer.
(c) University of Washington20-1 CSC 143 Java Trees.
CPS 100e 6.1 What’s the Difference Here? l How does find-a-track work? Fast forward?
CompSci Toward understanding data structures  What can be put in a TreeSet?  What can be sorted?  Where do we find this information?  How do.
Java: Base Types All information has a type or class designation
From doubly-linked lists to binary trees
Data and Information How and why do we organize data? Differences between data and information? What about knowledge?
Java: Base Types All information has a type or class designation
PFTFBH Binary Search trees Fundamental Data Structure
Binary Trees Linked lists: efficient insertion/deletion, inefficient search ArrayList: search can be efficient, insertion/deletion not Binary trees: efficient.
Plan for the Week Review Big-Oh
From data to information
Binary Trees Linked lists: efficient insertion/deletion, inefficient search ArrayList: search can be efficient, insertion/deletion not Binary trees: efficient.
PFTWBH More examples of recursion and alternatives
What’s the Difference Here?
Week 6 - Wednesday CS221.
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
Lecture 12 CS203 1.
CSC 143 Java Trees.
Java String Class String is a class
Linked lists Low-level (concrete) data structure, used to implement higher-level structures Used to implement sequences/lists (see CList in Tapestry) Basis.
Presentation transcript:

CompSci 100e 7.1 Plan for the week l Review:  Boggle  Coding standards and inheritance l Understand linked lists from the bottom up and top-down  As clients of java.util.LinkedList  As POJOs  Using linked lists to leverage algorithmic improvements l Binary Trees  Just a linked list with 2 pointers per node? l Self-referential structures and recursion  Why recursion works well with linked-structures l Lab: Memoizing  BoggleScore, SpreadingNews, and related APTs

CompSci 100e 7.2 Documentation l Standard identifiers  i, j, k : integer loop counters  n, len, length : integer number of elements in collection  x, y : cartesian coordinates (integer or real)  head,current,last : references used to iterate over lists. l Variable name guidelines  Use nouns that describe what value is being stored  Don’t reiterate the type involved l Comments for methods and classes  Abstraction : What does it do?  Implementation : How does it do it? l Inline comments as neeeded

CompSci 100e 7.3 What can an Object do (to itself)? l  Look at java.lang.Object  What is this class? What is its purpose? l toString()  Used to print ( System.out.println ) an object  overriding toString() useful in new classes  String concatenation: String s = "value "+ x;  Default is basically a pointer-value

CompSci 100e 7.4 What else can you do to an Object? l equals(Object o)  Determines if guts of two objects are the same, must override, e.g., for using a.indexOf(o) in ArrayList a  Default is ==, pointer equality l hashCode()  Hashes object (guts) to value for efficient lookup l If you're implementing a new class, to play nice with others you must  Override equals and hashCode  Ensure that equal objects return same hashCode value

CompSci 100e 7.5 Objects and values l Primitive variables are boxes  think memory location with value l Object variables are labels that are put on boxes String s = new String("genome"); String t = new String("genome"); if (s == t) {they label the same box} if (s.equals(t)) {contents of boxes the same} s t What's in the boxes? "genome" is in the boxes

CompSci 100e 7.6 Objects, values, classes l For primitive types: int, char, double, boolean  Variables have names and are themselves boxes (metaphorically)  Two int variables assigned 17 are equal with == l For object types: String, ArrayList, others  Variables have names and are labels for boxes  If no box assigned, created, then label applied to null  Can assign label to existing box (via another label)  Can create new box using built-in new l Object types are references/pointers/labels to storage

CompSci 100e 7.7 Anatomy of a class public class Foo { private int mySize; private String myName; public Foo(){ // what’s needed? } public int getSize(){ return mySize; } public double getArea(){ double x; x = Math.sqrt(mySize); return x; } l What values for vars (variables) and ivars (instance variables)?

CompSci 100e 7.8 Tomato and Tomato, how to code java.util.Collection and java.util.Collections  one is an interface add(), addAll(), remove(), removeAll(), clear() toArray(), size(), iterator()  one is a collection of static methods sort(), shuffle(), reverse(), max(), min() frequency(), binarySearch(), indexOfSubList() java.util.Arrays  Also a collection of static methods sort(), fill(), copyOf(), asList()

CompSci 100e 7.9 Methods, Interfaces, Inheritance l A method by any other name would smell as sweet  Method in OO languages, functions, procedures in others  Parameters and return value: communication Do objects or methods communicate?: OO v procedural Static : Math.sqrt, Character.isUpperCase, …  Don’t belong to an object, invoked via class (clue above?)  Java API helpful here l Interface: implement class with required, related methods  Map: HashMap, TreeMap  List: ArrayList, LinkedList, Stack, Vector

CompSci 100e 7.10 Interfaces continued l In the beginning  Make code work, don’t worry about generalizing  But, if you write code using Map rather than TreeMap Can swap in a new implementation, coded generally! l Don’t know how to optimize: space or time  Facilitate change: use interface rather than concrete class  My DVD connects to my TV, regardless of brand, why?  How do you turn on a Nokia cell phone? Motorola? But! l Interfaces facilitate code refactoring  Don’t add functionality, change speed or memory or …

CompSci 100e 7.11 What does Object-Oriented mean? l Very common method of organizing code  Design classes, which encapsulate state and behavior  Some classes can be similar to, but different from their parent class: inheritance Super class, subclass  Inherit behavior, use as is or modify and use or both l Complex to design a hierarchy of classes, but important  More of this in Compsci 108 or on-the-job training  We’re solving simple problems, not designing re-usable libraries l Simple does not mean straight-forward!

CompSci 100e 7.12 Inheritance and Interfaces l Interfaces provide method names and parameters  The method signature we can expect and thus use!  What can we do to an ArrayList? To a LinkedList?  What can we do to a Map or Set or PriorityQueue?  IAutoPlayer is an interface l Abstract classes can implement core, duplicated code  If we can add one object to a [set,map,list], can we add an entire list of objects? java.util.AbstractCollection  If we can iterate can we remove? Convert to array? Obtain size?  AbstractAutoPlayer is an interface

CompSci 100e 7.13 Miscellany l Inheritance and overriding  Inheritance is the process by which a Class assumes the properties of its Superclasses  An object checks its own methods before consulting the Superclass thus overriding the Superclass methods  Polymorphism : many classes respond to some common message. l Access Control  public : accessible anywhere  private : accessible only within methods of this class  protected : accessible to this class or subclasses  No modifier : accessible within class and package

CompSci 100e 7.14 Contrast LinkedList and ArrayList l See ISimpleList, SimpleLinkedList, SimpleArrayList  Meant to illustrate concepts, not industrial-strength  Very similar to industrial-strength, however l ArrayList --- why is access O(1) or constant time?  Storage in memory is contiguous, all elements same size  Where is the 1 st element? 40 th ? 360 th ?  Doesn’t matter what’s in the ArrayList, everything is a pointer or a reference (what about null?)

CompSci 100e 7.15 What about LinkedList? l Why is access of N th element linear time? l Why is adding to front constant-time O(1)? front

CompSci 100e 7.16 Linked list applications continued l If programming in C, there are no “growable-arrays”, so typically linked lists used when # elements in a collection varies, isn’t known, can’t be fixed at compile time  Could grow array, potentially expensive/wasteful especially if # elements is small.  Also need # elements in array, requires extra parameter  With linked list, one pointer used to access all the elements in a collection l Simulation/modeling of DNA gene-splicing  Given list of millions of CGTA… for DNA strand, find locations where new DNA/gene can be spliced in Remove target sequence, insert new sequence

CompSci 100e 7.17 Linked lists, CDT and ADT l As an ADT  A list is empty, or contains an element and a list  ( ) or (x, (y, ( ) ) ) l As a picture l As a CDT (concrete data type) pojo: plain old Java object public class Node { Node p = new Node(); String value; p.value = “hello”; Node next; p.next = null; } p 0

CompSci 100e 7.18 Building linked lists l Add words to the front of a list (draw a picture)  Create new node with next pointing to list, reset start of list public class Node { String value; Node next; Node(String s, Node link){ value = s; next = link; } // … declarations here Node list = null; while (scanner.hasNext()) { list = new Node(scanner.next(), list); } l What about adding to the end of the list?

CompSci 100e 7.19 Dissection of add-to-front l List initially empty l First node has first word l Each new word causes new node to be created  New node added to front l Rhs of operator = completely evaluated before assignment list A list = new Node(word,list); B Node(String s, Node link) { info = s; next = link;} list

CompSci 100e 7.20 Standard list processing (iterative) l Visit all nodes once, e.g., count them or process them public int size(Node list){ int count = 0; while (list != null) { count++; list = list.next; } return count; } l What changes in code if we generalize what process means?  Print nodes?  Append “s” to all strings in list?

CompSci 100e 7.21 Standard list processing (recursive) l Visit all nodes once, e.g., count them public int recsize(Node list) { if (list == null) return 0; return 1 + recsize(list.next); } l Base case is almost always empty list: null pointer  Must return correct value, perform correct action  Recursive calls use this value/state to anchor recursion  Sometimes one node list also used, two “base” cases l Recursive calls make progress towards base case  Almost always using list.next as argument

CompSci 100e 7.22 Recursion with pictures l Counting recursively int recsize(Node list){ if (list == null) return 0; return 1 + recsize(list.next); } recsize(Node list) return 1+ recsize(list.next) recsize(Node list) return 1+ recsize(list.next) recsize(Node list) return 1+ recsize(list.next) recsize(Node list) return 1+ recsize(list.next) System.out.println(recsize(ptr)); ptr

CompSci 100e 7.23 Recursion and linked lists l Print nodes in reverse order  Print all but first node and… Print first node before or after other printing? public void print(Node list) { if (list != null) { } print(list.next); System.out.println(list.info); print(list.next);

CompSci 100e 7.24 Binary Trees l Linked lists: efficient insertion/deletion, inefficient search  ArrayList: search can be efficient, insertion/deletion not l Binary trees: efficient insertion, deletion, and search  trees used in many contexts, not just for searching, e.g., expression trees  search in O(log n) like sorted array  insertion/deletion O(1) like list, once location found!  binary trees are inherently recursive, difficult to process trees non-recursively, but possible recursion never required, often makes coding simpler

CompSci 100e 7.25 From doubly-linked lists to binary trees l Instead of using prev and next to point to a linear arrangement, use them to divide the universe in half  Similar to binary search, everything less goes left, everything greater goes right  How do we search?  How do we insert? “llama” “tiger” “monkey” “jaguar” “elephant” “ giraffe ” “pig” “hippo” “leopard” “koala”

CompSci 100e 7.26 Basic tree definitions l Binary tree is a structure:  empty  root node with left and right subtrees l terminology: parent, children, leaf node, internal node, depth, height, path link from node N to M then N is parent of M –M is child of N leaf node has no children –internal node has 1 or 2 children path is sequence of nodes, N 1, N 2, … N k –N i is parent of N i+1 –sometimes edge instead of node depth (level) of node: length of root-to-node path –level of root is 1 (measured in nodes) height of node: length of longest node-to-leaf path –height of tree is height of root l Trees can have many shapes: short/bushy, long/stringy  If height is h, how many nodes in tree? A B ED F C G

CompSci 100e 7.27 A TreeNode by any other name… l What does this look like?  What does the picture look like? public class TreeNode { TreeNode left; TreeNode right; String info; TreeNode(String s, TreeNode llink, TreeNode rlink){ info = s; left = llink; right = rlink; } “llama” “tiger” “ giraffe ”

CompSci 100e 7.28 Printing a search tree in order l When is root printed?  After left subtree, before right subtree. void visit(TreeNode t) { if (t != null) { visit(t.left); System.out.println(t.info); visit(t.right); } l Inorder traversal l Big-Oh? “llama” “tiger” “monkey” “jaguar” “elephant” “ giraffe ” “pig” “hippo” “leopard”

CompSci 100e 7.29 Tree traversals l Different traversals useful in different contexts  Inorder prints search tree in order Visit left-subtree, process root, visit right-subtree  Preorder useful for reading/writing trees Process root, visit left-subtree, visit right-subtree  Postorder useful for destroying trees Visit left-subtree, visit right-subtree, process root “llama” “tiger” “monkey” “jaguar” “elephant” “ giraffe ”

CompSci 100e 7.30 Tree functions l Compute height of a tree, what is complexity? int height(Tree root) { if (root == null) return 0; else { return 1 + Math.max(height(root.left), height(root.right) ); } l Modify function to compute number of nodes in a tree, does complexity change?  What about computing number of leaf nodes?

CompSci 100e 7.31 Balanced Trees and Complexity l A tree is height-balanced if  Left and right subtrees are height-balanced  Left and right heights differ by at most one boolean isBalanced(Tree root) { if (root == null) return true; return isBalanced(root.left) && isBalanced(root.right) && Math.abs(height(root.left) – height(root.right)) <= 1; }

CompSci 100e 7.32 What is complexity? l Assume trees are “balanced” in analyzing complexity  Roughly half the nodes in each subtree  Leads to easier analysis l How to develop recurrence relation?  What is T(n)?  What other work is done? l How to solve recurrence relation  Plug, expand, plug, expand, find pattern  A real proof requires induction to verify correctness