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

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

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

CS61B Lecture #21: Tree Searching. Last modified: Wed Oct 12 19:23: CS61B: Lecture #21 1

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

Binary Trees

Binary Trees, Binary Search Trees

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

TREES Lecture 12 CS2110 Fall 2016

TREES. Trees - Introduction

CS61B Lecture #23. Today: Priority queues (Data Structures 6.4, 6.5) Range queries ( 6.2) Java utilities: SortedSet, Map, etc.

There are many other applications like constructing the expression tree from the postorder expression. I leave you with an idea as how to do it.

CS61B Lecture #23. Today: Priority queues (Data Structures 6.4, 6.5) Range queries ( 6.2) Java utilities: SortedSet, Map, etc.

Programming II (CS300)

Advanced Java Concepts Unit 5: Trees. Notes and Exercises

CS350: Data Structures Tree Traversal

TREES Lecture 10 CS2110 Spring2014

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

INF2220: algorithms and data structures Series 1

CE 221 Data Structures and Algorithms

Data Structures. Binary Trees. Root Level = 0. number of leaves:?? leaves Depth (Maximum level of the tree) leaves or nodes. Level=1.

First Semester - Question Bank Department of Computer Science Advanced Data Structures and Algorithms...

CSC148 Week 6. Larry Zhang

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

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

Binary Search Trees Treesort

March 20/2003 Jayakanth Srinivasan,

Data Structure Advanced

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

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

CSI33 Data Structures

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

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

TREES Lecture 12 CS2110 Spring 2018

Data Structures. Trees. By Dr. Mohammad Ali H. Eljinini. M.A. Eljinini, PhD

Chapter 20: Binary Trees

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

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

Data Structures and Algorithms for Engineers

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

Largest Online Community of VU Students

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

3137 Data Structures and Algorithms in C++

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

Recursive Data Structures and Grammars

Data Structures and Algorithms

Topics. Trees Vojislav Kecman. Which graphs are trees? Terminology. Terminology Trees as Models Some Tree Theorems Applications of Trees CMSC 302

Topic 14. The BinaryTree ADT

tree nonlinear Examples

An Introduction to Trees

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

1 Binary trees. 1 Binary search trees. 1 Traversal. 1 Insertion. 1 An empty structure is an empty tree.

Data Structure. IBPS SO (IT- Officer) Exam 2017

Tree Structures. A hierarchical data structure whose point of entry is the root node

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

Data Structures Question Bank Multiple Choice

Friday Four Square! 4:15PM, Outside Gates

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

Organizing Spatial Data

Why Do We Need Trees?

Trees. CSE 373 Data Structures

Binary Search Trees. See Section 11.1 of the text.

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

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

Advanced Java Concepts Unit 5: Trees. Notes and Exercises

DATA STRUCTURES AND ALGORITHMS. Hierarchical data structures: AVL tree, Bayer tree, Heap

INF2220: algorithms and data structures Series 1

Computer Science E-119 Fall Problem Set 4. Due prior to lecture on Wednesday, November 28

LECTURE 13 BINARY TREES

Section 5.5. Left subtree The left subtree of a vertex V on a binary tree is the graph formed by the left child L of V, the descendents

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

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

13 BINARY TREES DATA STRUCTURES AND ALGORITHMS INORDER, PREORDER, POSTORDER TRAVERSALS

Binary Trees and Binary Search Trees

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

Lecture #21: Search Trees, Sets. Last modified: Tue Mar 18 18:15: CS61A: Lecture #21 1

COMP 250 Fall binary trees Oct. 27, 2017

CMPSCI 187: Programming With Data Structures. Lecture #26: Binary Search Trees David Mix Barrington 9 November 2012

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

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

Binary Trees. Height 1

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

Outline. Computer Science 331. Insertion: An Example. A Recursive Insertion Algorithm. Binary Search Trees Insertion and Deletion.

CS24 Week 8 Lecture 1

CMSC 341. Binary Search Trees CMSC 341 BST

Partha Sarathi Mandal

» Access elements of a container sequentially without exposing the underlying representation

Revision Statement while return growth rate asymptotic notation complexity Compare algorithms Linear search Binary search Preconditions: sorted,

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

12 Abstract Data Types

Principles of Computer Science

Draw a diagram of an empty circular queue and describe it to the reader.

ECE Spring 2018 Problem Set #0 Due: 1/30/18

We have the pointers reference the next node in an inorder traversal; called threads

Why Use Binary Trees? Data Structures - Binary Trees 1. Trees (Contd.) Trees

About This Lecture. Trees. Outline. Recursive List Definition slide 1. Recursive Tree Definition. Recursive List Definition slide 2

Trees. T.U. Cluj-Napoca -DSA Lecture 2 - M. Joldos 1

Lecture Notes 16 - Trees CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson

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

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

LECTURE 11 TREE TRAVERSALS

Transcription:

CSB Lecture # A Recursive Structure Today: Trees Readings for Today: Data Structures, Chapter Readings for Next Topic: Data Structures, Chapter Trees naturally represent recursively defined, hierarchical objects with more than one recursive subpart for each instance. Common examples: expressions, sentences. Expressions have definitions such as an expression consists of a literal or two expressions separated by an operator. Also describe structures in which we recursively divide a set into multiple subsets. Last modified: Mon Oct 7 :: CSB: Lecture # Last modified: Mon Oct 7 :: CSB: Lecture # Fundamental Operation: Traversal Preorder Traversal and Prefix Expressions Traversing a tree means enumerating (some subset of) its nodes. Typically done recursively, because that is natural description. As nodes are enumerated, we say they are visited. Three basic orders for enumeration (+ variations): Problem: Convert z ( ( ( x (+ y 3))) z) Preorder: visit node, traverse its children. Postorder: traverse children, visit node. Inorder: traverse first child, visit node, traverse second child (binary trees only). 3 Postorder 3 Preorder 3 inorder Last modified: Mon Oct 7 :: CSB: Lecture # 3 x + y 3 (Tree<Label > is supposed to mean Tree whose labels have type Label.) static String tolisp (Tree<String> T) { return ""; else if (T.degree () == ) return T.label (); else { String R; R = ""; for (int i = ; i < T.numChildren (); i += ) R += " " + tolisp (T.child (i)); return String.format ("(%s%s)", T.label (), R); Last modified: Mon Oct 7 :: CSB: Lecture #

Inorder Traversal and Infix Expressions Problem: Convert x + z (((x(y+3)))z) To think about: how to get rid of all those parentheses. y 3 static String toinfix (Tree<String> T) { return ""; if (T.degree () == ) return T.label (); else { return String.format ("(%s%s%s)", toinfix (T.left ()), T.label (), toinfix (T.right ()) Last modified: Mon Oct 7 :: CSB: Lecture # Last modified: Mon Oct 7 :: CSB: Lecture # Postorder Traversal and Postfix Expressions Problem: Convert x + z y 3 x y 3 +: : : z : static String topolish (Tree<String> T) { return ""; else { String R; R = ""; for (int i = ; i < T.numChildren (); i += ) R += topolish (T.child (i)) + " "; return String.format ("%s%s:%d", R, T.label (), T.degree ()); Last modified: Mon Oct 7 :: CSB: Lecture # 7 A General Traversal: The Visitor Pattern void preordertraverse (Tree<Label> T, Action<Label> whattodo) { if (T!= null) { whattodo.action (T); for (int i = ; i < T.numChildren (); i += ) preordertraverse (T.child (i), whattodo); What is Action? interface Action<Label> { void action (Tree<Label> T); class Print implements Action<String> { preordertraverse (mytree, void action (Tree<String> T) { new Print ()); System.out.print (T.label ()); Last modified: Mon Oct 7 :: CSB: Lecture # 8

Times The traversal algorithms have roughly the form of the boom example in.3.3 of Data Structures an exponential algorithm. However, the role of M in that algorithm is played by the height of the tree, not the number of nodes. In fact, easy to see that tree traversal is linear: Θ(N), where N is the # of nodes: Form of the algorithm implies that there is one visit at the root, and then one visit for every edge in the tree. Since every node but the root has exactly one parent, and the root has none, must be N edges in any nonempty tree. In positional tree, is also one recursive call for each empty tree, but # of empty trees can be no greater than kn, where k is arity. For kary tree (max # children is k), h + N kh+ k, where h is height. So h Ω(log k N) = Ω(lg N) and h O(N). Many tree algorithms look at one child only. For them, time is proportional to the height of the tree, and this is Θ(lg N), assuming that tree is bushy each level has about as many nodes as possible. Last modified: Mon Oct 7 :: CSB: Lecture # 9 LevelOrder (BreadthFirst) Traversal Problem: Traverse all nodes at depth, then depth, etc: 3 One technique: Iterative Deepening. For each level, k, from to h, call dolevel(t,k) void dolevel (Tree T, int lev) { if (lev == ) visit T else for each nonnull child, C, of T { dolevel (C, lev); Last modified: Mon Oct 7 :: CSB: Lecture # Iterative Deepening Time? Iterative Traversals Tree recursion conceals data: a stack of nodes (all thetarguments) and a little extra information. Can make the data explicit, e.g.: 3 7 8 9 Let h be height, N be # of nodes. 3 Count # edges traversed (i.e, # of calls, not counting null nodes). First (full) tree: for level, 3 for level, 7 for level, for level 3. Or in general ( ) + ( ) +... + ( h+ ) = h+ h Θ(N), since N = h+ for this tree. Second (right leaning) tree: for level, for level, 3 for level 3. Or in general (h + )(h + )/ = N(N + )/ Θ(N ), since N = h + for this kind of tree. 3 void preordertraverse (Tree<Label> T, Action whattodo) { Stack<Label> s = new Stack<Label> (); s.push (T); while (! s.isempty ()) { Tree<Label> node = s.pop (); if (node == null) continue; whattodo.action (node); for (int i = node.numchildren (); i >= ; i = ) s.push (node.child (i)); To do a breadthfirst traversal, use a queue instead of a stack, replace push with add, and pop with removefirst. Makes breadthfirst traversal worstcase linear time in all cases, but also linear space for bushy trees. Last modified: Mon Oct 7 :: CSB: Lecture # Last modified: Mon Oct 7 :: CSB: Lecture #

Iterators for Trees Frankly, iterators are not terribly convenient on trees. But can use ideas from iterative methods. class PreorderTreeIterator<Label> implements Iterator<Label> { private Stack<Tree<Label>> s = new Stack<Tree<Label>> (); public PreorderTreeIterator (Tree<Label> T) { s.push (T); public boolean hasnext () { return! s.isempty (); public T next () { Tree<Label> result = s.pop (); for (int i = result.numchildren (); i >= ; i = ) s.push (result.child (i)); return result.label (); void remove () { throw new UnsupportedOperationException (); Example: (what do I have to add to class Tree first?) for (String label : atree) System.out.print (label + " "); Last modified: Mon Oct 7 :: CSB: Lecture # 3...... 3... (a) Embedded child pointers (+ optional parent pointers) 3......... (c) child/sibling pointers Tree Representation 3...... 3... (b) Array of child pointers (+ optional parent pointers) 3 (d) breadthfirst array (complete trees) Last modified: Mon Oct 7 :: CSB: Lecture # Divide and Conquer Much (most?) computation is devoted to finding things in response to various forms of query. Linear search for response can be expensive, especially when data set is too large for primary memory. Preferable to have criteria for dividing data to be searched into pieces recursively Remember figure for lg N algorithms: at µsec per comparison, could process 3 items in sec. Tree is a natural framework for the representation: decision data decision data Binary Search Property: Binary Search Trees Tree nodes contain keys, and possibly other data. All nodes in left subtree of node have smaller keys. All nodes in right subtree of node have larger keys. Smaller means any complete transitive, antisymmetric ordering on keys: exactly one of x y and y x true. x y and y z imply x z. (To simplify, won t allow duplicate keys this semester). E.g., in dictionary database, node label would be (word, definition): word is the key. no yes low mid high Last modified: Mon Oct 7 :: CSB: Lecture # Last modified: Mon Oct 7 :: CSB: Lecture #

Finding Inserting Searching for and 9: 9 3 9 / Node in T containing L, or null if none / static BST find(bst T, Key L) { return T; if (L.keyequals (T.label())) return T; else if (L T.label()) return find(t.left(), L); else return find(t.right (), L); Dashed boxes show which node labels we look at. Number looked at proportional to height of tree. Inserting 7 9 7 9 3 / Insert L in T, replacing existing value if present, and returning new tree. / BST insert(bst T, Key L) { return new BST(L); if (L.keyequals (T.label())) T.setLabel (L); else if (L T.label()) T.setLeft(insert (T.left (), L)); else T.setRight(insert (T.right (), L)); return T; Starred edges are set (to themselves, unless initially null). Again, time proportional to height. Last modified: Mon Oct 7 :: CSB: Lecture # 7 Last modified: Mon Oct 7 :: CSB: Lecture # 8 Deletion A Leap Ahead: Quadtrees 9 9 3 7 Initial 9 3 9 Remove 9 9 3 7 Remove 7 formerly contained 9 3 9 Remove Want to index information about locations so that items can be retrieved by position. Quadtrees do so using standard datastructuring trick: Divide and Conquer. Idea: divide (D) space into four quadrants, and store items in the appropriate quadrant. Repeat this recursively with each quadrant that contains more than one item. Original definition: a quadtree is either Empty, or An item at some position (x, y), called the root, plus four quadtrees, each containing only items that are northwest, northeast, southwest, and southeast of (x, y). Big idea is that if you are looking for point (x, y ) and the root is not the point you are looking for, you can narrow down which of the four subtrees of the root to look in by comparing coordinates (x, y) with (x,y ). Last modified: Mon Oct 7 :: CSB: Lecture # 9 Last modified: Mon Oct 7 :: CSB: Lecture #

Classical Quadtree: Example Pointregion (PR) Quadtrees E A C D B E A C D B If we use a QuadTree to track moving objects, it may be useful to be able to delete items from a tree: when an object moves, the subtree that it goes in may change. Difficult to do with the classical data structure above, so we ll define instead: A quadtree consists of a bounding rectangle, B and either Zero up to a small number of items that lie in that rectangle, or Four quadtrees whose bounding rectangles are the four quadrants of B (all of equal size). A D A completely empty quadtree can have an arbitrary bounding rectangle, or you can wait for the first point to be inserted. B E C B A C E D Last modified: Mon Oct 7 :: CSB: Lecture # Last modified: Mon Oct 7 :: CSB: Lecture # Example of PR Quadtree Navigating PR Quadtrees A B D C ( point per leaf) A B D C To find an item at (x,y) in quadtree T,. If (x,y) is outside the bounding rectangle of T, or T is empty, then (x,y) is not in T.. Otherwise, if T contains a small set of items, then (x,y) is in T iff it is among these items. 3. Otherwise, T consists of four quadtrees. Recursively look for (x, y) in each (however, step # above will cause all but one of these bounding boxes to reject the point immediately). Similar procedure works when looking for all items within some rectangle, R:. If R does not intersect the bounding rectangle of T, or T is empty, then there are no items in R.. Otherwise, if T contains a set of items, return those that are in R, if any. 3. Otherwise, T consists of four quadtrees. Recursively look for points in R in each one of them. Last modified: Mon Oct 7 :: CSB: Lecture # 3 Last modified: Mon Oct 7 :: CSB: Lecture #

Insertion into PR Quadtrees Various cases for inserting a new point N, showing initial state final state. (,) (,) (,) (,) N N (,) (,) (,) (,) (,) (,) (,) N (,) N (,) (,) (,) (,) Last modified: Mon Oct 7 :: CSB: Lecture #