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

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

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

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

TREES. Trees - Introduction

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

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

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

Data Structures Question Bank Multiple Choice

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

Binary Trees

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

Binary Trees, Binary Search Trees

COMP 250 Fall binary trees Oct. 27, 2017

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

Data Structure Advanced

Programming II (CS300)

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

Chapter 4 Trees. Theorem A graph G has a spanning tree if and only if G is connected.

CSI33 Data Structures

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

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

Advanced Java Concepts Unit 5: Trees. Notes and Exercises

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

CS24 Week 8 Lecture 1

LECTURE 11 TREE TRAVERSALS

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.

INF2220: algorithms and data structures Series 1

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

12 Abstract Data Types

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

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

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

March 20/2003 Jayakanth Srinivasan,

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

Chapter 20: Binary Trees

Computer Science 210 Data Structures Siena College Fall Topic Notes: 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. Virendra Singh Indian Institute of Science Bangalore Lecture 11. Courtesy: Prof. Sartaj Sahni. Sep 3,2010

3137 Data Structures and Algorithms in C++

MIDTERM EXAMINATION Spring 2010 CS301- Data Structures

COSC 2011 Section N. Trees: Terminology and Basic Properties

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

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

COMP 250 Fall recurrences 2 Oct. 13, 2017

CS350: Data Structures Tree Traversal

Topic 14. The BinaryTree ADT

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

Principles of Computer Science

An Introduction to Trees

CE 221 Data Structures and Algorithms

3. According to universal addressing, what is the address of vertex d? 4. According to universal addressing, what is the address of vertex f?

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

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

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

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

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

TREES Lecture 10 CS2110 Spring2014

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

Largest Online Community of VU Students

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

Stacks, Queues and Hierarchical Collections

Partha Sarathi Mandal

Advanced Java Concepts Unit 5: Trees. Notes and Exercises

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

Topic Binary Trees (Non-Linear Data Structures)

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


Recursive Data Structures and Grammars

Advanced Tree Data Structures

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

Stacks, Queues & Trees. The Stack Interface. The Stack Interface. Harald Gall, Prof. Dr.

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

tree nonlinear Examples

Data Structures and Algorithms for Engineers

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

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

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

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

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

6-TREE. Tree: Directed Tree: A directed tree is an acyclic digraph which has one node called the root node

Trees. Tree Structure Binary Tree Tree Traversals

Tree Data Structures CSC 221

TREES Lecture 12 CS2110 Fall 2016

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

Stacks, Queues and Hierarchical Collections. 2501ICT Logan

CS : Data Structures

CS : Data Structures

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

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

LECTURE 13 BINARY TREES

7.1 Introduction. A (free) tree T is A simple graph such that for every pair of vertices v and w there is a unique path from v to w

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

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

DATA STRUCTURE : A MCQ QUESTION SET Code : RBMCQ0305

Trees. CSE 373 Data Structures

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


4. Trees. 4.1 Preliminaries. 4.2 Binary trees. 4.3 Binary search trees. 4.4 AVL trees. 4.5 Splay trees. 4.6 B-trees. 4. Trees

Transcription:

CS61B Lecture #2: Trees Last modified: Wed Oct 12 12:49:46 216 CS61B: Lecture #2 1

A Recursive Structure 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: Wed Oct 12 12:49:46 216 CS61B: Lecture #2 2

Fundamental Operation: Traversal 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): Preorder: visit node, traverse its children. Postorder: traverse children, visit node. Inorder: traverse first child, visit node, traverse second child (binary trees only). 6 4 3 5 1 5 1 5 2 4 2 3 6 3 6 1 4 2 Postorder Preorder inorder Last modified: Wed Oct 12 12:49:46 216 CS61B: Lecture #2 3

Preorder Traversal and Prefix Expressions - - z Problem: Convert * (- (- (* x (+ y 3))) z) x + y 3 (Assume Tree<Label > is means Tree whose labels have type Label.) static String tolisp(tree<string> T) { if (T == null) return ""; else if (T.degree() == ) return T.label(); else { String R; R = ""; for (int i = ; i < T.numChildren(); i += 1) R += " " + tolisp(t.child(i)); return String.format("(%s%s)", T.label(), R); Last modified: Wed Oct 12 12:49:46 216 CS61B: Lecture #2 4

Problem: Convert - Inorder Traversal and Infix Expressions - * 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) { if (T == null) return ""; if (T.degree() == ) return T.label(); else { String left = toinfix(t.left()), right = toinfix(t.right()); return String.format("(%s%s%s)", left, T.label(), right); Last modified: Wed Oct 12 12:49:46 216 CS61B: Lecture #2 5

Postorder Traversal and Postfix Expressions Problem: Convert - - z * x y 3 +:2 *:2 -:1 z -:2 x + y 3 static String topolish(tree<string> T) { if (T == null) return ""; else { String R; R = ""; for (int i = ; i < T.numChildren(); i += 1) R += topolish(t.child(i)) + " "; return String.format("%s%s:%d", R, T.label(), T.degree()); Last modified: Wed Oct 12 12:49:46 216 CS61B: Lecture #2 6

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 += 1) preordertraverse(t.child(i), whattodo); What is Action? interface Action<Label> { void action(tree<label> T); Now, using Java 8 lambda syntax, I can print all labels in the tree in preorder with: preordertraverse(mytree, (Tree<String> T) -> System.out.print(T.label())); Last modified: Wed Oct 12 12:49:46 216 CS61B: Lecture #2 7

Iterative Depth-First Traversals Tree recursion conceals data: a stack of nodes (all thetarguments) and a little extra information. Can make the data explicit: void preordertraverse2(tree<label> T, Action whattodo) { Stack<Tree<Label>> s = new Stack<>(); s.push(t); while (!s.isempty()) { Tree<Label> node = s.pop(); if (node!= null) { whattodo.action(node); for (int i = node.numchildren()-1; i >= ; i -= 1) s.push(node.child(i)); // Why backward? To do a breadth-first traversal, use a queue instead of a stack, replace push with add, and pop with removefirst. Makes breadth-first traversal worst-case linear time in all cases, but also linear space for bushy trees. Last modified: Wed Oct 12 12:49:46 216 CS61B: Lecture #2 8

Level-Order (Breadth-First) Traversal Problem: Traverse all nodes at depth, then depth 1, etc: 1 2 3 4 5 6 Last modified: Wed Oct 12 12:49:46 216 CS61B: Lecture #2 9

Breadth-First Traversal Implemented A simple modification to iterative depth-first traversal gives breadthfirst traversal. Just change the (LIFO) stack to a (FIFO) queue: void preordertraverse2(tree<label> T, Action whattodo) { ArrayDeque<Tree<Label>> s = new ArrayDeque<>(); // (Changed) s.push(t); while (!s.isempty()) { Tree<Label> node = s.remove(); // (Changed) if (node!= null) { whattodo.action(node); for (int i = ; i < node.numchildren(); i += 1) // (Changed) s.push(node.child(i)); Last modified: Wed Oct 12 12:49:46 216 CS61B: Lecture #2 1

Times The traversal algorithms have roughly the form of the boom example in 1.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 1 edges in any non-empty 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 k-ary tree (max # children is k), h+1 N kh+1 1 k 1, where h is height. So h Ω(log k N) = Ω(lgN) 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 Θ(lgN), assuming that tree is bushy each level has about as many nodes as possible. Last modified: Wed Oct 12 12:49:46 216 CS61B: Lecture #2 11

Recursive Breadth-First Traversal: Iterative Deepening For each level, k, of the tree from to h, call dolevel(t,k): void dolevel(tree T, int lev) { if (lev == ) visit T else for each non-null child, C, of T { dolevel(c, lev-1); We do breadth-first traversal by repeated (truncated) depth-first traversals. In dolevel(t, k), we skip (i.e., traverse but don t visit) the nodes before level k, and then visit at level k, but not their children. Last modified: Wed Oct 12 12:49:46 216 CS61B: Lecture #2 12

Iterative Deepening Time? 1 2 1 3 4 5 6 2 7 8 9 1 11 12 13 14 3 Let h be height, N be # of nodes. Count # edges traversed (i.e, # of calls, not counting null nodes). First (full) tree: 1 for level, 3 for level 1, 7 for level 2, 15 for level 3. Or in general (2 1 1)+(2 2 1)+...+(2 h+1 1) = 2 h+2 h Θ(N), since N = 2 h+1 1 for this tree. Second (right leaning) tree: 1 for level, 2 for level 2, 3 for level 3. Or in general (h+1)(h+2)/2 = N(N +1)/2 Θ(N 2 ), since N = h+1 for this kind of tree. Last modified: Wed Oct 12 12:49:46 216 CS61B: Lecture #2 13

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()-1; i >= ; i -= 1) 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: Wed Oct 12 12:49:46 216 CS61B: Lecture #2 14

Tree Representation 1 2 3 1... 2... 3... (a) Embedded child pointers (+ optional parent pointers) 1 2 3......... (c) child/sibling pointers 1... 2... 3... (b) Array of child pointers (+ optional parent pointers) 1 2 3 (d) breadth-first array (complete trees) Last modified: Wed Oct 12 12:49:46 216 CS61B: Lecture #2 15