1 Trees Tree nomenclature Implementation strategies Traversals –Depth-first –Breadth-first Implementing binary trees Reading: L&C 9.1 – 9.7.

Slides:



Advertisements
Similar presentations
Binary Trees CSC 220. Your Observations (so far data structures) Array –Unordered Add, delete, search –Ordered Linked List –??
Advertisements

1 Heaps and Priority Queues Heap Definition and Operations Using Heaps –Heap sort –Priority queues Implementing heaps –With links –With arrays –Analysis.
Main Index Contents 11 Main Index Contents Week 6 – Binary Trees.
DictionaryADT and Trees. Overview What is the DictionaryADT? What are trees? Implementing DictionaryADT with binary trees Balanced trees DictionaryADT.
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.
Trees Chapter 8. Chapter 8: Trees2 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information To learn how.
Lists A list is a finite, ordered sequence of data items. Two Implementations –Arrays –Linked Lists.
Binary Trees A binary tree is made up of a finite set of nodes that is either empty or consists of a node called the root together with two binary trees,
Fall 2007CS 2251 Iterators and Tree Traversals. Fall 2007CS 2252 Binary Trees In a binary tree, each node has at most two subtrees A set of nodes T is.
© 2006 Pearson Addison-Wesley. All rights reserved11 A-1 Chapter 11 Trees.
Trees Chapter 25 Slides by Steve Armstrong LeTourneau University Longview, TX  2007,  Prentice Hall.
CS 261 – Winter 2010 Trees. Ubiquitous – they are everywhere in CS Probably ranks third among the most used data structure: 1.Vectors and Arrays 2.Lists.
Chapter 12 Trees. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Define trees as data structures Define the terms.
CHAPTER 12 Trees. 2 Tree Definition A tree is a non-linear structure, consisting of nodes and links Links: The links are represented by ordered pairs.
Marc Smith and Jim Ten Eyck
Binary and Other Trees CSE, POSTECH. 2 2 Linear Lists and Trees Linear lists are useful for serially ordered data – (e 1,e 2,e 3,…,e n ) – Days of week.
Version TCSS 342, Winter 2006 Lecture Notes Trees Binary Trees Binary Search Trees.
Chapter 18 - basic definitions - binary trees - tree traversals Intro. to Trees 1CSCI 3333 Data Structures.
1 Chapter 18 Trees Objective To learn general trees and recursion binary trees and recursion tree traversal.
Data Structures Arrays both single and multiple dimensions Stacks Queues Trees Linked Lists.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 9: Trees Java Software Structures: Designing and Using Data.
Trees & Graphs Chapter 25 Carrano, Data Structures and Abstractions with Java, Second Edition, (c) 2007 Pearson Education, Inc. All rights reserved X.
1 Trees Tree nomenclature Implementation strategies Traversals –Depth-first –Breadth-first Implementing binary search trees.
Tree. Basic characteristic Top node = root Left and right subtree Node 1 is a parent of node 2,5,6. –Node 2 is a parent of node.
Chapter 10 Trees – part B.
CS Data Structures Chapter 5 Trees. Chapter 5 Trees: Outline  Introduction  Representation Of Trees  Binary Trees  Binary Tree Traversals 
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.
Lecture 10 Trees –Definiton of trees –Uses of trees –Operations on a tree.
Topic 14 The BinaryTree ADT Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms.
Trees CSCI Objectives Define trees as data structures Define the terms associated with trees Discuss the possible implementations of trees Analyze.
Spring 2010CS 2251 Trees Chapter 6. Spring 2010CS 2252 Chapter Objectives Learn to use a tree to represent a hierarchical organization of information.
CISC220 Fall 2009 James Atlas Lecture 13: Trees. Skip Lists.
CMSC 341 Introduction to Trees. 8/3/2007 UMBC CMSC 341 TreeIntro 2 Tree ADT Tree definition  A tree is a set of nodes which may be empty  If not empty,
Chapter 10-A Trees Modified
Tree (new ADT) Terminology:  A tree is a collection of elements (nodes)  Each node may have 0 or more successors (called children)  How many does a.
data ordered along paths from root to leaf
Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
Compiled by: Dr. Mohammad Omar Alhawarat
Topic 15 The Binary Search Tree ADT Binary Search Tree A binary search tree (BST) is a binary tree with an ordering property of its elements, such.
Trees Isaac Sheff. Nodes Building blocks of trees “Parent” node may have “Child” nodes Can be both parent and child Can’t be its own ancestor Can’t have.
1 Trees and Binary Search Trees Using binary trees Definition of a binary search tree Implementing binary search trees –Add Element –Remove Element Using.
Trees : Part 1 Section 4.1 (1) Theory and Terminology (2) Preorder, Postorder and Levelorder Traversals.
IKI 10100I: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100I: Data.
Min Chen School of Computer Science and Engineering Seoul National University Data Structure: Chapter 6.
PRIORITY QUEUES AND HEAPS Slides of Ken Birman, Cornell University.
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.
CMSC 341 Introduction to Trees. 2/21/20062 Tree ADT Tree definition –A tree is a set of nodes which may be empty –If not empty, then there is a distinguished.
1 Trees and Binary Search Trees Using binary trees Definition of a binary search tree Implementing binary search trees –Add Element –Remove Element Using.
Trees Ellen Walker CPSC 201 Data Structures Hiram College.
1 Trees General Trees  Nonrecursive definition: a tree consists of a set of nodes and a set of directed edges that connect pairs of nodes.
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.
CMSC 202, Version 5/02 1 Trees. CMSC 202, Version 5/02 2 Tree Basics 1.A tree is a set of nodes. 2.A tree may be empty (i.e., contain no nodes). 3.If.
BINARY TREES Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary.
1 Trees General Trees  Nonrecursive definition: a tree consists of a set of nodes and a set of directed edges that connect pairs of nodes.
Trees Chapter 19, 20 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
1 Trees : Part 1 Reading: Section 4.1 Theory and Terminology Preorder, Postorder and Levelorder Traversals.
Chapter 10 Trees © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
Trees CSIT 402 Data Structures II 1. 2 Why Do We Need Trees? Lists, Stacks, and Queues are linear relationships Information often contains hierarchical.
1 CMSC 341 Introduction to Trees Textbook sections:
IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture13.
TREES From root to leaf. Trees  A tree is a non-linear collection  The elements are in a hierarchical arrangement  The elements are not accessible.
The Tree ADT.
Trees Chapter 15.
Trees Tree nomenclature Implementation strategies Traversals
CSE 373 Data Structures Lecture 7
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.
Java Software Structures: John Lewis & Joseph Chase
Trees.
Binary Trees.
Presentation transcript:

1 Trees Tree nomenclature Implementation strategies Traversals –Depth-first –Breadth-first Implementing binary trees Reading: L&C 9.1 – 9.7

Tree Nomenclature 2 Node Edge Root Level 2 Leaf Siblings Parent Child Height Path

3 Tree Nomenclature A tree is a non-linear structure in which elements are organized into a hierarchy A tree has levels of nodes connected by edges Each node is at a level in the tree The root node is the one node at the top level Nodes are children of nodes at higher levels Nodes with the same parent node are siblings A leaf is a node with no children

4 Tree Nomenclature A path exists from the root to any node or leaf A node is the ancestor of another node if it is on the path between the root and the other node A node that can be reached along a path away from the root is a descendant The level of a node is the length of the path (number of edges) from the root to the node The height of a tree is the length of the longest path from the root to a leaf

5 Tree Nomenclature A tree is considered to be balanced if all of the leaves are at the same level or within one level of each other A tree is considered to be complete if it is balanced and all the leaves on the bottom level are on the left A tree is considered full if all leaves of the tree are at the same level and every node is either a leaf or has exactly n children The height of a balanced, complete, or full tree that contains N elements is log n N

6 Tree Nomenclature The order of a tree is an important characteristic It is based on the maximum number of children a node can have –There is no limit in a general tree –An n-ary tree has a limit of n children per node –A binary tree has exactly two children per node The maze in Project 4 will be a “tri-nary” tree Binary trees are often useful, so we’ll concentrate on them in the rest of this course

7 Implementation Strategies The computational strategy for an array In a binary tree, for any element stored in the array in position n, we consider: –its left child to be stored in position: 2*n + 1 –its right child to be stored in position: 2*(n + 1) This is a simple numerical index mapping and can be managed by adding capacity as needed Its disadvantage is that it may waste memory If the tree is not complete or nearly complete, the array may have many empty elements

8 Implementation Strategies The simulated link strategy for an array In a binary tree, each element of the array is an object with a reference to a data element and an int index for each of its two children A new child is always added to the end of the contiguous storage area in the array to avoid wasting space However, there is increased overhead to remove an element from the array (to shift the remaining elements and alter index values as required)

Implementation Strategies A BC DE F Tree Computational Strategy in an Array ABC [0][1][2][3][4][5][6][7] Simulated Link Strategy in an Array (added in the order A, C, B, E, D, F) A 21 CB -- EDF - [0][1][2][3][4][5] Wasted Space (B’s children) [8][9][10][11][12] Wasted Space (B’s grandchildren) Wasted (E Child) [13][14] Wasted Space (D’s children) FED

10 Implementation Strategies For a binary tree, the linked strategy uses a node class containing a reference to the data and a left and a right reference to two child nodes F -- Root A BC -- D - E --

11 Traversals Types of traversals –Pre-order (Depth first) Visit node, traverse left child, traverse right child –In-order (Depth first) Traverse left child, visit node, traverse right child –Post-Order (Depth first) Traverse left child, traverse right child, visit node –Level-order (Breadth first) Visit all the nodes at each level, one level at a time

12 Traversals A BC DE Tree Pre-order traversal would give: A, B, D, E, C In-order traversal would give: D, B, E, A, C Post-order traversal would give: D, E, B, C, A Level-order Traversal would give: A, B, C, D, E

13 Level-order Traversal A possible algorithm for level-order traversal Create a queue called nodes Create an unordered list called results Enqueue a reference to the root node onto the nodes queue While the nodes queue is not empty Dequeue the first element If it is not null add it to the rear of the results list Enqueue the children of the element on the nodes queue Else Add null to the rear of the results list Return an iterator for the results list

14 Implementing Binary Trees A possible interface definition is provided that can be used on any binary tree regardless of the purpose of the tree Note: There is no method for adding an element or removing an element yet Until we know more about the purpose of the tree, those operations can’t be defined We will use a less general (child) interface for a binary search tree and a heap later

15 Implementing Binary Trees > BinaryTreeADT + removeLeftSubtree( ) : void + removeRightSubtree( ) : void + removeAllElements( ) : void + isEmpty( ) : boolean + size( ) : int + contains( ) : boolean + find( ) : T + toString( ) : String + iteratorInOrder( ) : Iterator + iteratorPreOrder( ) : Iterator + iteratorPostOrder( ) : Iterator + iteratorLevelOrder( ) : Iterator Note: toString is missing in L&C Fig 9.9 LinkedBinaryTree # count : int # root : BinaryTreeNode {Three constructors as shown in text}

16 Implementing Binary Trees Here we use a BinaryTreeNode in a linked strategy for our implementation Note: L&C code allows “package” access to the BinaryTreeNode attributes - not accessor methods as would be better O-O practice BinaryTreeNode # element : T # left : BinaryTreeNode # right : BinaryTreeNode + BinaryTreeNode (obj : T) + numChildren ( ) : int

17 Implementing Binary Trees Three constructors for convenience: –One to instantiate an empty tree –One to instantiate a tree with one root node –One to instantiate a tree with a root node and left and right child nodes from existing trees In normal methods for processing a binary tree, it is useful to use recursive algorithms

18 Implementing Binary Trees BinaryTreeNode method to get number of children public int numChildren() { int children = 0; if (left != null) children = 1 + left.numChildren(); if (right != null) children += 1 + right.numChildren(); return children; } Note: Usual strategy of keeping a count attribute doesn’t work well since if we add a child to a node, we need to go back to all parent nodes to update the count attribute in each of them

19 Implementing Binary Trees LinkedBinaryTree remove left sub-tree method public void removeLeftSubtree() { // Note: uses methods instead of package access if (root.getLeft() != null) count = count – root.getLeft().numChildren() – 1; root.setLeft(null); // creates garbage! } The Java garbage collection approach saves coding effort here In languages like C++, the last line would be a “memory leak” This method would be much more complex to implement - needing to release objects’ memory

20 Implementing Binary Trees LinkedBinaryTree method to find target private BinaryTreeNode findagain (T target, BinaryTreeNode next) { // Note: uses methods instead of package access if (next == null) return null; if (next.getElement().equals(target)) return next; BinaryTreeNode temp = findagain(target, next.getLeft()); if (temp == null) temp = findagain(target, next.getRight()); return temp; }

21 Implementing Binary Trees LinkedBinaryTree method iteratorInOrder() public Iterator iteratorInOrder() { ArrayList list = new ArrayList (); inOrder (root, list); return list.iterator(); } private void inorder(BinaryTreeNode node, ArrayList list) { // Note: uses methods instead of package access if (node != null) { inorder(node.getLeft(), list); list.add(node.getElement()); inorder(node.getRight(), list); }