References and Homework ABSTRACT DATA TYPES; LISTS & TREES. Abstract Data Type (ADT) 9/24/14. ADT example: Set (bunch of different values)

Similar documents
TREES Lecture 10 CS2110 Spring2014

TREES Lecture 12 CS2110 Fall 2016

TREES. Tree Overview 9/28/16. Prelim 1 tonight! Important Announcements. Tree terminology. Binary trees were in A1!

TREES Lecture 12 CS2110 Spring 2018

TREES 11/1/18. Prelim Updates. Data Structures. Example Data Structures. Tree Overview. Tree. Singly linked list: Today: trees!

Programming II (CS300)

CS301 - Data Structures Glossary By

TREES. Trees - Introduction

Binary Trees

Recursive Data Structures and Grammars

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

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

Trees. (Trees) Data Structures and Programming Spring / 28

Computer Science 210 Data Structures Siena College Fall Topic Notes: Trees

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

Trees. CSE 373 Data Structures

Why Do We Need Trees?

CISC 235 Topic 3. General Trees, Binary Trees, Binary Search Trees

Binary Trees, Binary Search Trees

CS24 Week 8 Lecture 1

TREES Lecture 12 CS2110 Spring 2019

PRIORITY QUEUES AND HEAPS

Chapter 20: Binary Trees

Topic 14. The BinaryTree ADT

Abstract vs concrete data structures HEAPS AND PRIORITY QUEUES. Abstract vs concrete data structures. Concrete Data Types. Concrete data structures

CS 231 Data Structures and Algorithms Fall Recursion and Binary Trees Lecture 21 October 24, Prof. Zadia Codabux

CS61BL. Lecture 3: Asymptotic Analysis Trees & Tree Traversals Stacks and Queues Binary Search Trees (and other trees)

Data Structure - Binary Tree 1 -

MIDTERM EXAMINATION Spring 2010 CS301- Data Structures

Trees 11/15/16. Chapter 11. Terminology. Terminology. Terminology. Terminology. Terminology

Trees. Dr. Ronaldo Menezes Hugo Serrano Ronaldo Menezes, Florida Tech

CSC148 Week 6. Larry Zhang

COSC 2007 Data Structures II Final Exam. Part 1: multiple choice (1 mark each, total 30 marks, circle the correct answer)

CS61B Lecture #20: Trees. Last modified: Mon Oct 8 21:21: CS61B: Lecture #20 1

CS302 - Data Structures using C++

Trees. Q: Why study trees? A: Many advance ADTs are implemented using tree-based data structures.

FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 ( Marks: 1 ) - Please choose one The data of the problem is of 2GB and the hard

Garbage Collection: recycling unused memory

Tree. A path is a connected sequence of edges. A tree topology is acyclic there is no loop.

Course Review for. Cpt S 223 Fall Cpt S 223. School of EECS, WSU

CS61B Lecture #20. Today: Trees. Readings for Today: Data Structures, Chapter 5. Readings for Next Topic: Data Structures, Chapter 6

3137 Data Structures and Algorithms in C++

CS61B Lecture #20: Trees. Last modified: Wed Oct 12 12:49: CS61B: Lecture #20 1

The Java Collections Framework. Chapters 7.5

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

Computational Optimization ISE 407. Lecture 16. Dr. Ted Ralphs

Abstract Data Structures IB Computer Science. Content developed by Dartford Grammar School Computer Science Department

Also, recursive methods are usually declared private, and require a public non-recursive method to initiate them.

PRIORITY QUEUES AND HEAPS

Todays Lecture. Assignment 2 deadline: You have 5 Calendar days to complete.

CSCI-401 Examlet #5. Name: Class: Date: True/False Indicate whether the sentence or statement is true or false.

CE 221 Data Structures and Algorithms

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct.

Algorithms in Systems Engineering ISE 172. Lecture 16. Dr. Ted Ralphs

CSE 230 Intermediate Programming in C and C++ Binary Tree

tree nonlinear Examples

Data Structures Question Bank Multiple Choice

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

Stacks, Queues and Hierarchical Collections

Programming II (CS300)

Trees : Part 1. Section 4.1. Theory and Terminology. A Tree? A Tree? Theory and Terminology. Theory and Terminology

Binary Tree. Preview. Binary Tree. Binary Tree. Binary Search Tree 10/2/2017. Binary Tree

Lecture 12 TREES II CS2110 Spring 2018

Terminology. The ADT Binary Tree. The ADT Binary Search Tree

Uses for Trees About Trees Binary Trees. Trees. Seth Long. January 31, 2010

1. Stack overflow & underflow 2. Implementation: partially filled array & linked list 3. Applications: reverse string, backtracking

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

CS61B Lecture #21. A Recursive Structure. Fundamental Operation: Traversal. Preorder Traversal and Prefix Expressions. (- (- (* x (+ y 3))) z)

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

Principles of Computer Science

Lec 17 April 8. Topics: binary Trees expression trees. (Chapter 5 of text)

PRIORITY QUEUES AND HEAPS

Name CPTR246 Spring '17 (100 total points) Exam 3

Trees! Ellen Walker! CPSC 201 Data Structures! Hiram College!

Lecture: Analysis of Algorithms (CS )

Summer Final Exam Review Session August 5, 2009

BBM 201 Data structures

CSI33 Data Structures

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

Stacks, Queues and Hierarchical Collections. 2501ICT Logan

Lecture 4. The Java Collections Framework

COMP Analysis of Algorithms & Data Structures

A set of nodes (or vertices) with a single starting point

Trees, Part 1: Unbalanced Trees

Module 4: Index Structures Lecture 13: Index structure. The Lecture Contains: Index structure. Binary search tree (BST) B-tree. B+-tree.

Largest Online Community of VU Students

Trees. Truong Tuan Anh CSE-HCMUT

CMPT 225. Binary Search Trees

BST Implementation. Data Structures. Lecture 4 Binary search trees (BST) Dr. Mahmoud Attia Sakr University of Ain Shams

Tree: non-recursive definition. Trees, Binary Search Trees, and Heaps. Tree: recursive definition. Tree: example.

Final Exam Data Structure course. No. of Branches (5)

12 Abstract Data Types

Advanced Java Concepts Unit 5: Trees. Notes and Exercises

COMP Analysis of Algorithms & Data Structures

Algorithms. Deleting from Red-Black Trees B-Trees

Upcoming ACM Events Linux Crash Course Date: Time: Location: Weekly Crack the Coding Interview Date:

Chapter 8: Data Abstractions

Chapter 5. Binary Trees

ECE250: Algorithms and Data Structures Midterm Review

Transcription:

9// References and Homework Text: Chapters, and ABSTRACT DATA TYPES; LISTS & TREES Homework: Learn these List methods, from http://docs.oracle.com/javase/7/docs/api/java/util/list.html add, addall, contains, containsall, get, indexof, isempty, lastindexof, remove, size, toarray mylist = new List(someOtherList) mylist = new List(Collection<T>) Also useful: Arrays.asList() Lecture CS Fall Abstract Data Type (ADT) ADT example: Set (bunch of different values) 6 An Abstract Data Type, or ADT: A type (set of values together with operations on them), where: We state in some fashion what the operations do We may give constraints on the operations, such as how much they cost (how much time or space they must take) We use ADTs to help describe and implement many important data structures used in computer science, e.g.: set, bag list or sequence, stack, queue map, dictionary tree, binary tree, BST graph Set of values: Values of some type E (e.g. int) Typical operations:. Create an empty set (using a new-expression). size() size of the set 3. add(v) add value v to the set (if it is not in). delete(v) delete v from the set (if it is in). isin(v) = v is in the set Constraints: size takes constant time. add, delete, isin take expected (average) constant time but may take time proportional to the size of the set. We learn about hashing later on, it gives us such an implementation Java Collections Framework Java Collections Framework 7 Java comes with a bunch of interfaces and classes for implementing some ADTs like sets, lists, trees. Makes it EASY to use these things. Defined in package java.util. Homework: Peruse these two classes in the API package: ArrayList<E>: Implement a list or sequence some methods: add(e) add(i, e) remove(i) remove(e) indexof(e) lastindexof(e) contains(e) get(i) set(i, e) size() isempty() Vector<E>: Like ArrayList, but an older class They use an array to implement the list! i: a position. First is e: an object of class E 9 Homework: Peruse following in the API package: LinkedList<E>: Implement a list or sequence some methods: add(e) add(i, e) remove(i) remove(e) indexof(e) lastindexof(e) contains(e) get(i) set(i, e) size() isempty() getfirst() getlast() Uses a doubly linked list to implement the list or sequence of values i: a position. First is e: an object of class E

9// Stack<E> in java.util Queue not in java.util Stack<E>: Implements a stack: size() isempty() push(e) pop() peek() Queue Implement a queue: size() isempty() push(e) pop() peek() Stack is actually a subclass of Vector, So you can use all of Vector s methods peek: get top or first value but don t remove it Stack LIFO last in first out TREES Queue: FIFO first in first out Lecture CS Fall 3 Readings & Homework on Trees Tree Overview 8 Textbook: Chapter 3 Trees Chapter Tree Implementations Assignment # Collision Detection Based on bounding box trees Tree: recursive data structure (similar to list) Each node may have zero or more successors (children) Each node has exactly one predecessor (parent) except the root, which has none All nodes are reachable from root Binary tree: tree in which each node can have at most two children: a left child and a right child 9 General tree Not a tree Binary tree 6 8 List-like tree Binary Trees were in A! Tree Terminology You have seen a binary tree in A. An elephant has a mom and pop. There is an ancestral tree! elephant mom pop mom pop mom M: root of this tree G: root of the left subtree of M M B, H, J, N, S: leaves N: left child of P; S: right child G W P: parent of N M and G: ancestors of D D J P P, N, S: descendents of W B H N J is at depth (i.e. length of path from root = no. of edges) W is at height (i.e. length of longest path to a leaf) A collection of several trees is called a...? S

9// 3 Class for Binary Tree Node class TreeNode<T> { private T datum; private TreeNode<T> left, right; /** Constructor: one node tree with datum x */ public TreeNode (T x) { datum= x; /** Constr: Tree with root value x, left tree lft, right tree rgt */ public TreeNode (T x, TreeNode<T> lft, TreeNode<T> rgt) { datum= x; left= lft; right= rgt; Points to left subtree Points to right subtree more methods: getdatum, setdatum, getleft, setleft, etc. Binary versus general tree In a binary tree each node has exactly two pointers: to the left subtree and to the right subtree Of course one or both could be null In a general tree, a node can have any number of child nodes Very useful in some situations Class for General Tree nodes class GTreeNode {. private Object datum;. private GTreeCell left; 3. private GTreeCell sibling;. appropriate getters/setters Parent node points directly only to its leftmost child Leftmost child has pointer to next sibling, which points to next sibling, etc. 9 3 9 3 General tree Tree represented using GTreeCell 6 Applications of Trees Most languages (natural and computer) have a recursive, hierarchical structure This structure is implicit in ordinary textual representation Recursive structure can be made explicit by representing sentences in the language as trees: Abstract Syntax Trees (ASTs) ASTs are easier to optimize, generate code from, etc. than textual representation A parser converts textual representations to AST Example Recursion on Trees 7 8 Expression grammar: E integer E (E + E) Text AST Representation -3-3 Recursive methods can be written to operate on trees in an obvious way In textual representation Parentheses show hierarchical structure ( + 3) + 3 Base case empty tree leaf node In tree representation Hierarchy is explicit in the structure of the tree ((+3) + (+7)) + + + Recursive case solve problem on left and right subtrees put solutions together to get solution for full tree 3 7 3

9// Searching in a Binary Tree Searching in a Binary Tree 9 /** Return true iff x is the datum in a node of tree t*/ public static boolean treesearch(object x, TreeNode t) { if (t == null) return false; if (t.datum.equals(x)) return true; return treesearch(x, t.left) treesearch(x, t.right); 3 /** Return true iff x is the datum in a node of tree t*/ public static boolean treesearch(object x, TreeNode t) { if (t == null) return false; if (t.datum.equals(x)) return true; return treesearch(x, t.left) treesearch(x, t.right); Analog of linear search in lists: given tree and an object, find out if object is stored in tree Easy to write recursively, harder to write iteratively 9 8 3 7 Important point about t. We can think of it either as () One node of the tree OR () The subtree that is rooted at t 9 8 3 7 Binary Search Tree (BST) Building a BST 3 If the tree data are ordered: in every subtree, All left descendents of node come before node All right descendents of node come after node 8 Search is MUCH faster 3 7 9 /** Return true iff x if the datum in a node of tree t. Precondition: node is a BST */ public static boolean treesearch (Object x, TreeNode t) { if (t== null) return false; if (t.datum.equals(x)) return true; if (t.datum.compareto(x) > ) return treesearch(x, t.left); else return treesearch(x, t.right); 3 To insert a new item Pretend to look for the item Put the new node in the place where you fall off the tree This can be done using either recursion or iteration Example Tree uses alphabetical order Months appear for insertion in calendar order apr jan feb mar jun jul may What Can Go Wrong? Printing Contents of BST 33 A BST makes searches very fast, unless Nodes are inserted in alphabetical order In this case, we re basically building a linked list (with some extra wasted space for the left fields that aren t being used) BST works great if data arrives in random order apr feb jan jul jun mar may 3 /** Print the BST in alpha. order. */ Because of ordering rules for a BST, it s easy public void show () { to print the items in show(root); alphabetical order System.out.println(); Recursively print left subtree /** Print BST t in alpha order */ Print the node private static void show(treenode t) { Recursively print if (t== null) return; right subtree show(t.lchild); System.out.print(t.datum); show(t.rchild);

9// 3 Tree Traversals Walking over whole tree is a tree traversal Done often enough that there are standard names Previous example: inorder traversal n Process left subtree n Process node n Process right subtree Note: Can do other processing besides printing Other standard kinds of traversals Preorder traversal w Process node w Process left subtree w Process right subtree Postorder traversal w Process left subtree w Process right subtree w Process node Level-order traversal w Not recursive uses a queue 36 Some Useful Methods /** Return true iff node t is a leaf */ public static boolean isleaf(treenode t) { return t!= null && t.left == null && t.right == null; /** Return height of node t using postorder traversal public static int height(treenode t) { if (t== null) return -; //empty tree if (isleaf(t)) return ; return + Math.max(height(t.left), height(t.right)); /** Return number of nodes in t using postorder traversal */ public static int nnodes(treenode t) { if (t== null) return ; return + nnodes(t.left) + nnodes(t.right); Useful Facts about Binary Trees Tree with Parent Pointers 37 Max number of nodes at depth d: d If height of tree is h min number of nodes in tree: h + Max number of nodes in tree: + + h = h+ depth Height, maximum number of nodes 38 In some applications, it is useful to have trees in which nodes can reference their parents Analog of doubly-linked lists Complete binary tree All levels of tree down to a certain depth are completely filled Height, minimum number of nodes Things to Think About Suffix Trees 39 What if we want to delete data from a BST? A BST works great as long as it s balanced How can we keep it balanced? This turns out to be hard enough to motivate us to create other kinds of trees apr jan feb mar jun jul may Given a string s, a suffix tree for s is a tree such that each edge has a unique label, which is a nonnull substring of s any two edges out of the same node have labels beginning with different characters the labels along any path from the root to a leaf concatenate together to give a suffix of s all suffixes are represented by some path the leaf of the path is labeled with the index of the first character of the suffix in s Suffix trees can be constructed in linear time

9// Suffix Trees Suffix Trees a dabra$ bra $ ra Useful in string matching algorithms (e.g., longest common substring of strings) Most algorithms linear time Used in genomics (human genome is ~GB) dabra$ $ bra $ $ $ abra Huffman Trees Huffman Compression of Ulysses 3 e 97 e t a s 63 6 Fixed length encoding 97* + 63* + * + 6* = 6 Huffman encoding 97* + 63* + *3 + 6*3 = t a s ' ' 3 'e' 3996 3 't' 966 'a' 896 'o' 8888 'n' 786 'i' 76 's' 7386 'h' 686 'r' 683 'l' 67 'u' 39 6 'g' 6 6 'f' 8 6 '.' 36 6 'p' 66 6 Huffman Compression of Ulysses BSP Trees (c.f. k-d trees)... 7 BSP = Binary Space Partition (not related to BST!) '7' 68 '/' 8 'X' 9 6 '&' 3 8 '%' 3 9 '+' 9 original size 93 compressed size 68.7% compression Used to render 3D images of polygons, e.g., Doom engine http://www.bogotobogo.com/games/spatialdatastructure.php Example: Axis-aligned BSP Tree Each non-leaf node n represents a region & splitting plane p Left subtree of n contains all sub-regions on one side of p Right subtree of n contains all sub-regions on the other side of p Leaf nodes represent regions with associated data (e.g., geometry) 6

9// 8 Tree Summary A tree is a recursive data structure Each cell has or more successors (children) Each cell except the root has at exactly one predecessor (parent) All cells are reachable from the root A cell with no children is called a leaf Special case: binary tree Binary tree cells have a left and a right child Either or both children can be null Trees are useful for exposing the recursive structure of natural language and computer programs 9 A: Collision Detection Axis-aligned Bounding Box Trees (AABB-Trees) Object partitioning Build one on each shape Do tree-tree queries to detect overlapping shapes Some GUI material Available on CMS Due October, :9 pm Demo! 7