csci 210: Data Structures Trees

Similar documents
COSC 2011 Section N. Trees: Terminology and Basic Properties

COMP26120: Algorithms and Imperative Programming. Lecture 1 Trees

Why Do We Need Trees?

Trees. Data structures and Algorithms. Make Money Fast! Bank Robbery. Stock Fraud. Ponzi Scheme

interface Position<E> { E getelement() throws IllegalStateExcept..; }

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

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

Announcements. Midterm exam 2, Thursday, May 18. Today s topic: Binary trees (Ch. 8) Next topic: Priority queues and heaps. Break around 11:45am

Binary Trees, Binary Search Trees

Algorithms and Data Structures

Trees. CSE 373 Data Structures

Programming II (CS300)

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

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

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

Algorithms. Deleting from Red-Black Trees B-Trees

Hierarchical data structures. Announcements. Motivation for trees. Tree overview

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

Trees. Introduction & Terminology. February 05, 2018 Cinda Heeren / Geoffrey Tien 1

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

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

Trees, Part 1: Unbalanced Trees

Queues. ADT description Implementations. October 03, 2017 Cinda Heeren / Geoffrey Tien 1

Trees. Eric McCreath

Trees. Trees. CSE 2011 Winter 2007

Binary Trees

CSCI212 Computer Science. Binary Trees/Heaps/Binary Search Trees

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

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

Red-Black Trees. Based on materials by Dennis Frey, Yun Peng, Jian Chen, and Daniel Hood

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

BBM 201 Data structures

Lecture 6: Analysis of Algorithms (CS )

OUTLINE. General Trees (Ch. 7.1) Binary Trees (Ch. 7.3) Tree Traversals (Ch. 7.2)

Trees. A tree is a directed graph with the property

Outline. Preliminaries. Binary Trees Binary Search Trees. What is Tree? Implementation of Trees using C++ Tree traversals and applications

Data Structures Lecture 6

Learning Goals. CS221: Algorithms and Data Structures Lecture #3 Mind Your Priority Queues. Today s Outline. Back to Queues. Priority Queue ADT

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

Algorithms. AVL Tree

TREES. Trees - Introduction

Implementazione Alberi Binari. mediante. Linked Structure ( 7.3.4)

Recursive Data Structures and Grammars

BRONX COMMUNITY COLLEGE of the City University of New York DEPARTMENT OF MATHEMATICS AND COMPUTER SCIENCE

Universidad Carlos III de Madrid

Data Structures Brett Bernstein

Topic 14. The BinaryTree ADT

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

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

Binary Search Trees. Analysis of Algorithms

Principles of Computer Science

Algorithms and Data Structures CS-CO-412

Sorted Arrays. Operation Access Search Selection Predecessor Successor Output (print) Insert Delete Extract-Min

CS302 - Data Structures using C++

Week 2. TA Lab Consulting - See schedule (cs400 home pages) Peer Mentoring available - Friday 8am-12pm, 12:15-1:30pm in 1289CS

Binary trees. Binary trees. Binary trees

Cpt S 122 Data Structures. Data Structures Trees

(2,4) Trees Goodrich, Tamassia (2,4) Trees 1

CS24 Week 8 Lecture 1

Analysis of Algorithms

Advanced Set Representation Methods

Outline. Binary Tree

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

CMSC 341 Priority Queues & Heaps. Based on slides from previous iterations of this course

COMP : Trees. COMP20012 Trees 219

CMPT 225. Binary Search Trees

INF2220: algorithms and data structures Series 1

Lecture: Analysis of Algorithms (CS )

A Hierarchical Structure. Lecture11: Tree I. Tree Data Structures. Unix/Linux file systems. Bohyung Han CSE, POSTECH

Trees (Part 1, Theoretical) CSE 2320 Algorithms and Data Structures University of Texas at Arlington

Binary Trees. Recursive definition. Is this a binary tree?

COMP 250. Lecture 22. binary search trees. Oct. 30, 2017

Chapter 20: Binary Trees

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

COMP171. AVL-Trees (Part 1)

Priority Queues. Priority Queues Trees and Heaps Representations of Heaps Algorithms on Heaps Building a Heap Heapsort.

(2,4) Trees. 2/22/2006 (2,4) Trees 1

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

Data Structures and Algorithms

CSCI 136 Data Structures & Advanced Programming. Lecture 25 Fall 2018 Instructor: B 2

CS350: Data Structures Red-Black Trees

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

Trees, Binary Trees, and Binary Search Trees

CSE 100 Advanced Data Structures

CSI33 Data Structures

Garbage Collection: recycling unused memory

Binary Trees. Height 1

Trees: examples (Family trees)

Data Structures and Algorithms

CSCI2100B Data Structures Trees

Introduction. for large input, even access time may be prohibitive we need data structures that exhibit times closer to O(log N) binary search tree

CIS265/ Trees Red-Black Trees. Some of the following material is from:

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

CMSC 341 Lecture 14: Priority Queues, Heaps

Binary Search Trees > = 2014 Goodrich, Tamassia, Goldwasser. Binary Search Trees 1

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

Trees. Make Money Fast! Bank Robbery. Ponzi Scheme. Stock Fraud Goodrich, Tamassia, Goldwasser Trees

Why Trees? Alternatives. Want: Ordered arrays. Linked lists. A data structure that has quick insertion/deletion, as well as fast search

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

Transcription:

csci 210: Data Structures Trees 1

Summary Topics general trees, definitions and properties interface and implementation tree traversal algorithms depth and height pre-order traversal post-order traversal binary trees properties interface implementation binary search trees definition h-n relationship search, insert, delete performance READING: GT textbook chapter 7 and 10.1 2

Trees So far we have seen linear structures linear: before and after relationship lists, vectors, arrays, stacks, queues, etc Non-linear structure: trees probably the most fundamental structure in computing hierarchical structure Terminology: from family trees (genealogy) 3

store elements hierarchically Trees root the top element: root except the root, each element has a parent each element has 0 or more children 4

Trees Definition A tree T is a set of nodes storing elements such that the nodes have a parent-child relationship that satisfies the following if T is not empty, T has a special tree called the root that has no parent each node v of T different than the root has a unique parent node w; each node with parent w is a child of w Recursive definition T is either empty or consists of a node r (the root) and a possibly empty set of trees whose roots are the children of r Terminology siblings: two nodes that have the same parent are called siblings internal nodes nodes that have children external nodes or leaves nodes that don t have children ancestors descendants 5

Trees root internal nodes leaves 6

Trees ancestors of u u 7

Trees descendants of u u 8

Application of trees Applications of trees class hierarchy in Java file system storing hierarchies in organizations 9

Tree ADT Whatever the implementation of a tree is, its interface is the following root() size() isempty() parent(v) children(v) isinternal(v) isexternal(v) isroot() 10

Tree Implementation class Tree { TreeNode root; } //tree ADT methods.. class TreeNode<Type> { Type data; int size; TreeNode parent; TreeNode firstchild; TreeNode nextsibling; } getparent(); getchild(); getnextsibling(); 11

Algorithms on trees: Depth Depth: depth(t, v) is the number of ancestors of v, excluding v itself Recursive formulation if v == root, then depth(v) = 0 else, depth(v) is 1 + depth (parent(v)) Compute the depth of a node v in tree T: int depth(t, v) Algorithm: int depth(t,v) { if T.isRoot(v) return 0 return 1 + depth(t, T.parent(v)) } Analysis: O(number of ancestors) = O(depth_v) in the worst case the path is a linked-list and v is the leaf ==> O(n), where n is the number of nodes in the tree 12

Algorithms on trees: Height Height: height of a node v in T is the length of the longest path from v to any leaf Recursive formulation: if v is leaf, then its height is 0 else height(v) = 1 + maximum height of a child of v Definition: the height of a tree is the height of its root Compute the height of tree T: int height(t,v) Height and depth are symmetrical Proposition: the height of a tree T is the maximum depth of one of its leaves. 13

Height Algorithm: int height(t,v) { if T.isExternal(v) return 0; int h = 0; for each child w of v in T do h = max(h, height(t, w)) return h+1; } Analysis: total time: the sum of times spent at all nodes in all recursive calls the recursion: v calls height(w) recursively on all children w of v height() will eventually be called on every descendant of v overall: height() is called on each node precisely once, because each node has one parent aside from recursion for each node v: go through all children of v O(1 + c_v) where c_v is the number of children of v over all nodes: O(n) + SUM (c_v) each node is child of only one node, so its processed once as a child SUM(c_v) = n - 1 total: O(n), where n is the number of nodes in the tree 14

Tree traversals A traversal is a systematic way to visit all nodes of T. pre-order: root, children parent comes before children; overall root first post-order: children, root parent comes after children; overall root last void preorder(t, v) visit v for each child w of v in T do preorder(w) void postorder(t, v) for each child w of v in T do postorder(w) visit v Analysis: O(n) [same arguments as before] 15

Examples Tree associated with a document Pape r Title Abstract Ch1 Ch2 Ch3 Refs 1.1 1.2 3.1 3.2 In what order do you read the document? 16

Example Tree associated with an arithmetical expression + 3 * - + 12 5 1 7 Write method that evaluates the expression. In what order do you traverse the tree? 17

Binary trees 18

Binary trees Definition: A binary tree is a tree such that every node has at most 2 children each node is labeled as being either a left chilld or a right child Recursive definition: a binary tree is empty; or it consists of a node (the root) that stores an element a binary tree, called the left subtree of T a binary tree, called the right subtree of T Binary tree interface left(v) right(v) hasleft(v) hasright(v) + isinternal(v), is External(v), isroot(v), size(), isempty() 19

In a binary tree level 0 has <= 1 node level 1 has <= 2 nodes level 2 has <= 4 nodes... level i has <= 2^i nodes Properties of binary trees d=0 d=1 d=2 d=3 Proposition: Let T be a binary tree with n nodes and height h. Then h+1 <= n <= 2 h+1-1 lg(n+1) - 1 <= h <= n-1 20

Binary tree implementation use a linked-list structure; each node points to its left and right children ; the tree class stores the root node and the size of the tree implement the following functions: left(v) BTreeNode: parent right(v) hasleft(v) data hasright(v) isinternal(v) left right is External(v) isroot(v) size() isempty() also insertleft(v,e) insertright(v,e) remove(e) addroot(e) 21

Binary tree operations insertleft(v,e): create and return a new node w storing element e, add w as the left child of v an error occurs if v already has a left child insertright(v,e) remove(v): remove node v, replace it with its child, if any, and return the element stored at v an error occurs if v has 2 children addroot(e): create and return a new node r storing element e and make r the root of the tree; an error occurs if the tree is not empty attach(v,t1, T2): attach T1 and T2 respectively as the left and right subtrees of the external node v an error occurs if v is not external 22

Performance all O(1) left(v) right(v) hasleft(v) hasright(v) isinternal(v) is External(v) isroot(v) size() isempty() addroot(e) insertleft(v,e) insertright(v,e) remove(e) 23

Binary tree traversals Binary tree computations often involve traversals pre-order: root left right post-order: left right root additional traversal for binary trees in-order: left root right visit the nodes from left to right Exercise: write methods to implement each traversal on binary trees 24

Application: Tree drawing Come up with a solution to draw a binary tree in the following way. Essentially, we need to assign coordinate x and y to each node. node v in the tree x(v) =? y(v) =? 0 1 2 3 4 0 1 2 3 4 5 6 7 25

Application: Tree drawing We can use an in-order traversal and assign coordinate x and y of each node in the following way: x(v) is the number of nodes visited before v in the in-order traversal of v y(v) is the depth of v 0 1 2 3 4 0 1 2 3 4 5 6 7 26

Binary tree searching write search(v, k) search for element k in the subtree rooted at v return the node that contains k return null if not found performance? 27

Binary Search Trees (BST) Motivation: want a structure that can search fast arrays: search fast, updates slow linked lists: search slow, updates fast Intuition: tree combines the advantages of arrays and linked lists Definition: a BST is a binary tree with the following search property for any node v v k allows to search efficiently T1 T2 all nodes in T1<= k all node in T2 > k 28

BST v k Example T1 T2 <= k > k 29

Sorting a BST Print the elements in the BST in sorted order 30

Sorting a BST Print the elements in the BST in sorted order. in-order traversal: left -node-right Analysis: O(n) //print the elements in tree of v in order sort(bstnode v) if (v == null) return; sort(v.left()); print v.getdata(); sort(v.right()); 31

Searching in a BST 32

Searching in a BST //return the node w such that w.getdata() == k or null if such a node //does not exist BSTNode search (v, k) { if (v == null) return null; if (v.getdata() == k) return v; if (k < v.getdata()) return search(v.left(), k); else return search(v.right(), k) } Analysis: search traverses (only) a path down from the root does NOT traverse the entire tree O(depth of result node) = O(h), where h is the height of the tree 33

Inserting in a BST insert 25 34

Inserting in a BST insert 25 There is only one place where 25 can go 25 //create and insert node with key k in the right place void insert (v, k) { //this can only happen if inserting in an empty tree if (v == null) return new BSTNode(k); if (k <= v.getdata()) { if (v.left() == null) { //insert node as left child of v u = new BSTNode(k); v.setleft(u); } else { return insert(v.left(), k); } } else //if (v.getdata() > k) {... } } 35

Inserting in a BST Analysis: similar with searching traverses a path from the root to the inserted node O(depth of inserted node) this is O(h), where h is the height of the tree 36

Deleting in a BST delete 87 delete 21 delete 90 case 1: delete a leaf x if x is left of its parent, set parent(x).left = null else set parent(x).right = null case 2: delete a node with one child link parent(x) to the child of x case 2: delete a node with 2 children?? 37

Deleting in a BST delete 90 u copy in u 94 and delete 94 or the left-most child of right(x) node has <=1 child copy in u 87 and delete 87 the right-most child of left(x) node has <=1 child 38

Deleting in a BST Analysis: traverses a path from the root to the deleted node and sometimes from the deleted node to its left-most child this is O(h), where h is the height of the tree 39

BST performance Because of search property, all operations follow one root-leaf path insert: O(h) delete: O(h) search: O(h) We know that in a tree of n nodes h >= lg (n+1) - 1 h <= n-1 So in the worst case h is O(n) BST insert, search, delete: O(n) just like linked lists/arrays 40

BST performance worst-case scenario start with an empty tree insert 1 insert 2 insert 3 insert 4... insert n it is possible to maintain that the height of the tree is Theta(lg n) at all times by adding additional constraints perform rotations during insert and delete to maintain these constraints Balanced BSTs: h is Theta(lg n) Red-Black trees AVL trees 2-3-4 trees B-trees to find out more... take csci231 ( Algorithms) 41