Trees Tree nomenclature Implementation strategies Traversals

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.
Computer Science C++ High School Level By Guillermo Moreno.
1 Trees Tree nomenclature Implementation strategies Traversals –Depth-first –Breadth-first Implementing binary trees Reading: L&C 9.1 – 9.7.
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.
1 Trees What is a Tree? Tree terminology Why trees? General Trees and their implementation N-ary Trees N-ary Trees implementation Implementing trees Binary.
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.
Binary Trees Chapter 6.
Version TCSS 342, Winter 2006 Lecture Notes Trees Binary Trees Binary Search Trees.
1 Chapter 18 Trees Objective To learn general trees and recursion binary trees and recursion tree traversal.
1 Trees Tree nomenclature Implementation strategies Traversals –Depth-first –Breadth-first Implementing binary search trees.
Chapter 10 Trees – part B.
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.
COSC 1030 Lecture 9 Binary Trees. Topics Basic Concept and Terminology Applications of Binary Tree Complete Tree Representation Traversing Binary Trees.
Chapter 10-A Trees Modified
Topic 17 Introduction to Trees
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.
1 Trees and Binary Search Trees Using binary trees Definition of a binary search tree Implementing binary search trees –Add Element –Remove Element Using.
IKI 10100I: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100I: Data.
M180: Data Structures & Algorithms in Java Trees & Binary Trees Arab Open University 1.
1 Trees and Binary Search Trees Using binary trees Definition of a binary search tree Implementing binary search trees –Add Element –Remove Element Using.
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 Trees What is a Tree? Tree terminology Why trees? What is a general tree? Implementing trees Binary trees Binary tree implementation Application of Binary.
BINARY TREES Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary.
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.
Trees Saurav Karmakar
The Tree ADT.
CSE373: Data Structures & Algorithms
Data Structures and Design in Java © Rick Mercer
CC 215 Data Structures Trees
CSCE 210 Data Structures and Algorithms
CMSC 341 Introduction to Trees 8/3/2007 CMSC 341 Tree Intro.
Trees and Binary Search Trees
Lecture Trees Chapter 9 of textbook 1. Concepts of trees
Trees Another Abstract Data Type (ADT)
Binary Trees "A tree may grow a thousand feet tall, but its leaves will return to its roots." -Chinese Proverb.
Trees Trees are a very useful data structure. Many different kinds of trees are used in Computer Science. We shall study just a few of these.
CMSC 341 Introduction to Trees.
Trees What is a Tree? Tree terminology Why trees?
Lecture 18. Basics and types of Trees
Cse 373 April 14th – TreEs pt 2.
Week 11 - Friday CS221.
CSE 373 Data Structures Lecture 7
Binary Trees Lecture 36 Wed, Apr 21, /21/2018 Binary Trees.
Chapter 22 : Binary Trees, AVL Trees, and Priority Queues
Data Structures and Database Applications Binary Trees in C#
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.
TREES General trees Binary trees Binary search trees AVL trees
Trees 7/14/2009.
Java Software Structures: John Lewis & Joseph Chase
Trees CSE 373 Data Structures.
Trees Another Abstract Data Type (ADT)
Trees.
Topic 18 Binary Trees "A tree may grow a thousand feet tall, but its leaves will return to its roots." -Chinese Proverb.
Trees Another Abstract Data Type (ADT)
Trees CMSC 202, Version 5/02.
CMSC 202 Trees.
CMSC 341 Introduction to Trees CMSC 341 Tree Intro.
CS 261 – Data Structures Trees.
Binary Tree Properties & Representation
Important Problem Types and Fundamental Data Structures
Binary Trees.
Trees CSE 373 Data Structures.
Trees CSE 373 Data Structures.
Presentation transcript:

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

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

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

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

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 logn N

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

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

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 Computational Strategy in an Array [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] A B C D E F Wasted Space (B’s children) Wasted Space (B’s grandchildren) Wasted Space (D’s children) Wasted (E Child) Tree A Simulated Link Strategy in an Array (added in the order A, C, B, E, D, F) B C [0] [1] [2] [3] [4] [5] D E A C B E D F 2 1 4 3 - - - 5 - - - - F

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 Root A B C - - D E - - - F - -

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

Traversals 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 Tree A B C D E

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

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

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

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<T> # element : T # left : BinaryTreeNode # right : BinaryTreeNode + BinaryTreeNode (obj : T) + numChildren ( ) : int

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

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

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

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

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