1 Nell Dale Chapter 9 Trees Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.

Slides:



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

1 A full binary tree A full binary tree is a binary tree in which all the leaves are on the same level and every non leaf node has two children. SHAPE.
1 Nell Dale Chapter 9 Trees Plus Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
1 A Two-Level Binary Expression ‘-’ ‘8’ ‘5’ treePtr INORDER TRAVERSAL : has value 3 PREORDER TRAVERSAL: POSTORDER TRAVERSAL: 8 5 -
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
1 Jake’s Pizza Shop Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len.
Binary Trees, Binary Search Trees COMP171 Fall 2006.
Trees Chapter 8.
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.
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.
1 C++ Plus Data Structures Nell Dale Chapter 10 Sorting and Searching Algorithms Slides by Sylvia Sorkin, Community College of Baltimore County - Essex.
Priority Queues, Heaps CS3240, L. grewe 1. 2 Goals Describe a priority queue at the logical level and implement a priority queue as a list Describe the.
Heaps CS 308 – Data Structures.
Chapter 9 Heaps and Priority Queues. 9-2 What is a Heap? A heap is a binary tree that satisfies these special SHAPE and ORDER properties: –Its shape must.
C++ Plus Data Structures
Unit 11a 1 Unit 11: Data Structures & Complexity H We discuss in this unit Graphs and trees Binary search trees Hashing functions Recursive sorting: quicksort,
Binary Tree Properties & Representation. Minimum Number Of Nodes Minimum number of nodes in a binary tree whose height is h. At least one node at each.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Fundamentals of Python: From First Programs Through Data Structures
1 CS308 Data Structures An application of binary trees: Binary Expression Trees.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County.
9 Priority Queues, Heaps, and Graphs. 9-2 What is a Heap? A heap is a binary tree that satisfies these special SHAPE and ORDER properties: –Its shape.
1 Nell Dale Chapter 6 Lists Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
1 Nell Dale Chapter 9 Trees Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
Heaps and Priority Queues CS 3358 – Data Structures.
TREES A tree's a tree. How many more do you need to look at? --Ronald Reagan.
Trees. Tree Terminology Chapter 8: Trees 2 A tree consists of a collection of elements or nodes, with each node linked to its successors The node at the.
Computer Science and Software Engineering University of Wisconsin - Platteville 12. Heap Yan Shi CS/SE 2630 Lecture Notes Partially adopted from C++ Plus.
12-CRS-0106 REVISED 8 FEB 2013 CSG2A3 ALGORITMA dan STRUKTUR DATA.
Trees.ppt1 Introduction Many data structures are linear –unique first component –unique last component –other components have unique predecessor and successor.
CS 1031 Tree Traversal Techniques; Heaps Tree Traversal Concept Tree Traversal Techniques: Preorder, Inorder, Postorder Full Trees Almost Complete Trees.
1 Lecture 11 POLYNOMIALS and Tree sort 2 INTRODUCTION EVALUATING POLYNOMIAL FUNCTIONS Horner’s method Permutation Tree sort.
Binary Trees Chapter Definition And Application Of Binary Trees Binary tree: a nonlinear linked list in which each node may point to 0, 1, or two.
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.
Spring 2010CS 2251 Trees Chapter 6. Spring 2010CS 2252 Chapter Objectives Learn to use a tree to represent a hierarchical organization of information.
1 Trees A tree is a data structure used to represent different kinds of data and help solve a number of algorithmic problems Game trees (i.e., chess ),
Chapter 9 Priority Queues, Heaps, Graphs, and Sets.
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.
Binary Trees, Binary Search Trees RIZWAN REHMAN CENTRE FOR COMPUTER STUDIES DIBRUGARH UNIVERSITY.
1 Chapter 10 Trees. 2 Definition of Tree A tree is a set of linked nodes, such that there is one and only one path from a unique node (called the root.
1 Nell Dale Chapter 8 Binary Search Trees Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data.
Advance Data Structure 1 College Of Mathematic & Computer Sciences 1 Computer Sciences Department م. م علي عبد الكريم حبيب.
CPSC 252 Binary Heaps Page 1 Binary Heaps A complete binary tree is a binary tree that satisfies the following properties: - every level, except possibly.
TREES K. Birman’s and G. Bebis’s Slides. Tree Overview 2  Tree: recursive data structure (similar to list)  Each cell may have zero or more successors.
1 C++ Plus Data Structures Nell Dale Chapter 5 Linked Structures Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex.
1. Iterative Preorder Traversal Rpreorder(T) 1. [process the root node] if T!= NULL then Write Data(T) else Write “empty Tree” 2. [process the left subtree]
Copyright © 2012 Pearson Education, Inc. Chapter 20: Binary Trees.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 20: Binary Trees.
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.
2 Binary Heaps What if we’re mostly concerned with finding the most relevant data?  A binary heap is a binary tree (2 or fewer subtrees for each node)
Heaps CS 302 – Data Structures Sections 8.8, 9.1, and 9.2.
1 Nell Dale Chapter 8 Binary Search Trees Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
Chapter 9 Heaps and Priority Queues Lecture 18. Full Binary Tree Every non-leaf node has two children Leaves are on the same level Full Binary Tree.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 20: Binary Trees.
Data Structure By Amee Trivedi.
C++ Plus Data Structures
Binary Trees, Binary Search Trees
Chapter 20: Binary Trees.
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.
Chapter 9 Priority Queues, Heaps, Graphs, and Sets
Chapter 21: Binary Trees.
CS Data Structures Chapter 17 Heaps Mehmet H Gunes
CS Data Structures Chapter 17 Heaps Mehmet H Gunes
Binary Trees, Binary Search Trees
Heaps and Priority Queues
C++ Plus Data Structures
Binary Tree Traversal.
CMSC 341 Binary Search Trees 2/21/2006.
Binary Trees, Binary Search Trees
Presentation transcript:

1 Nell Dale Chapter 9 Trees Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures

2 Expressions With Binary Operators l l l 818*23 l 945/3 l These arithmetic expressions use BINARY OPERATORS that accept two operands

3 Evaluating Expressions With Binary Operators l (2+5)*2/3 l This expression is evaluated by using precedence rules l The parenthesized expression is solved first, then the multiplication is carried out and next the division l If we store expressions in a BST, we will not need parenthesis to communicate the order of precedence. The order of precedence is conveyed through the various levels of BST

4 A special kind of binary tree in which: 1. Each leaf node contains a single operand, 2. Each non-leaf node contains a single binary operator, and 3. The left and right subtrees of an operator node represent subexpressions that must be evaluated before applying the operator at the root of the subtree. A Binary Expression Tree is...

5 A Two-Level Binary Expression ‘-’ ‘8’ ‘5’ treePtr INORDER TRAVERSAL : has value 3 PREORDER TRAVERSAL: POSTORDER TRAVERSAL: 8 5 -

6 Levels Indicate Precedence When a binary expression tree is used to represent an expression, the levels of the nodes in the tree indicate their relative precedence of evaluation. Operations at higher levels of the tree are evaluated later than those below them. The operation at the root is always the last operation performed.

7 A Binary Expression Tree ‘*’ ‘+’ ‘4’ ‘3’ ‘2’ What value does it have? ( ) * 3 = 18

8 A Binary Expression Tree ‘*’ ‘+’ ‘4’ ‘3’ ‘2’ What infix, prefix, postfix expressions does it represent?

9 A Binary Expression Tree ‘*’ ‘+’ ‘4’ ‘3’ ‘2’ Infix: ( ( ) * 3 ) Prefix: * Postfix: * has operators in order used

10 Inorder Traversal: (A + H) / (M - Y) ‘/’ ‘+’ ‘A’ ‘H’ ‘-’ ‘M’‘Y’ tree Print left subtree firstPrint right subtree last Print second

11 Preorder Traversal: / + A H - M Y ‘/’ ‘+’ ‘A’ ‘H’ ‘-’ ‘M’‘Y’ tree Print left subtree secondPrint right subtree last Print first

12 ‘/’ ‘+’ ‘A’ ‘H’ ‘-’ ‘M’‘Y’ tree Print left subtree firstPrint right subtree second Print last Postorder Traversal: A H + M Y - /

13 Evaluate this binary expression tree ‘*’ ‘-’ ‘8’ ‘5’ What infix, prefix, postfix expressions does it represent? ‘/’ ‘+’ ‘4’ ‘3’ ‘2’

14 A binary expression tree Infix: ( ( ) * ( ( ) / 3 ) ) Prefix: * / Postfix: / * has operators in order used ‘*’ ‘-’ ‘8’ ‘5’ ‘/’ ‘+’ ‘4’ ‘3’ ‘2’

15 InfoNode has 2 forms enum OpType { OPERATOR, OPERAND } ; struct InfoNode { OpType whichType; union// ANONYMOUS union { char operation ; int operand ; } };. whichType. operation OPERATOR ‘+’. whichType. operand OPERAND 7

16 Each node contains two pointers struct TreeNode { InfoNode info ; // Data member TreeNode* left ; // Pointer to left child TreeNode* right ; // Pointer to right child };. left. info. right NULL whichType. operand OPERAND 7

17 Storing Information l tree  info.whichtype = OPERATOR; l tree  info.operation = ‘+’; l Next time, we can store an operand in the same node by the following statements l tree  info.whichtype = OPERAND; l tree  info.operand = 24;

int Eval ( TreeNode* ptr ) // Pre: ptr is a pointer to a binary expression tree. // Post: Function value = the value of the expression represented // by the binary tree pointed to by ptr. { switch ( ptr->info.whichType ) { case OPERAND : return ptr->info.operand ; case OPERATOR : switch ( tree->info.operation ) { case ‘+’ : return ( Eval ( ptr->left ) + Eval ( ptr->right ) ) ; case ‘-’ : return ( Eval ( ptr->left ) - Eval ( ptr->right ) ) ; case ‘*’ : return ( Eval ( ptr->left ) * Eval ( ptr->right ) ) ; case ‘/’ : return ( Eval ( ptr->left ) / Eval ( ptr->right ) ) ; } 18

19 class ExprTree ‘*’ ‘+’ ‘4’ ‘3’ ‘2’ ExprTree ~ExprTree Build Evaluate. private: root

20 Storing BST into an array (Left-to-Right, Level by Level)

21 Relationships l Node 0’s children are in nodes 1 and 2 l Node 1’s children are in nodes 3 and 4 l Node 2’s children are in nodes 5 and 6 l Node n’s children are in nodes 2n+1 and 2n+2 l From half point (NumElements/2) to last element are the leaf nodes l Node n’s parent is in (n-1)/2 l Array implementation works well with full trees

22 A full binary tree A full binary tree is a binary tree in which all the leaves are on the same level and every non leaf node has two children. SHAPE OF A FULL BINARY TREE

23 A complete binary tree A complete binary tree is a binary tree that is either full or full through the next-to-last level, with the leaves on the last level as far to the left as possible. (WARNING: It is not necessary to have a complete left side) SHAPE OF A COMPLETE BINARY TREE

24 Array Storage of non-complete trees l If some children are missing in higher levels, we store a dummy value in the array e.g. a negative number

25 What is a Heap? A heap is a binary tree (not a BST) that satisfies these special SHAPE and ORDER properties: n Its shape must be a complete binary tree. n For each node in the heap, the value stored in that node is greater than or equal to the value in each of its children. n This heap is different from the heap (free storage) available to programs using dynamic memory allocation

26 Heaps are Complete Trees l By shape, Heaps are complete binary trees l Complete does not mean *full* l A heap exactly follows the definition of a complete binary tree on slide 23 l A heap must be full until the second last level l A heap may or may not be full on the last level l The left subtree may or may not be full but all the elements in the left subtree should be as far to the left as possible!!

27 Storing Heaps into Arrays l With the above properties in mind, check the heap given in the worksheet l See how it is stored it in an array l Can you verify the relationship between parents and children? l Parent of a node is (n-1)/2 l Left child is 2n+1; right child is 2n+2 (if it exists) l Delete node E from the heap; does it alter the relationships?

28 Are these both heaps? C A T treePtr

tree Is this a heap?

tree Where is the largest element in a heap always found?

tree We can number the nodes left to right by level this way

tree And use the numbers as array indexes to store the tree [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] tree.nodes

33 Implementing Heap l We define the heap as a struct because mostly heaps are not used alone. They are used in combination with classes implementing other functions l We store heap elements in arrays as it becomes easier to manage them and because of their shape property, we do not have to store dummy nodes

// HEAP SPECIFICATION struct HeapType { void ReheapDown ( int root, int bottom ) ; void ReheapUp ( int root, int top ) ; // Different from text int* elements ; // ARRAY to be allocated dynamically int numElements ; }; 34

35 Maintaining Heap l Maintaining Heap is not easy l When we delete an element from the heap, we have to copy a node from the bottom in its place to maintain the shape l But the heap loses its order property l We must swap elements until we fix this problem l Consider the problem shown in the next slides when the root node is deleted

36

37

38 ReHeapDown l We call the function ReHeapDown that pushes down the element that violates the heap order property until the problem is fixed l It is a recursive function that takes the index of the current node in violation and the index of the bottom element l The Heap is to be fixed between the current node and the bottom element

39 ReHeapDown l Each time ReHeapDown is called, we go down one level thus we satisfy the smaller caller criterea for recursion l There are two base cases where we stop: n If elements[root] is a leaf n If heap order property is satisfied

40 // IMPLEMENTATION OF RECURSIVE HEAP MEMBER FUNCTIONS void HeapType::ReheapDown ( int root, int bottom ) // Pre: root is the index of the node that may violate the heap // order property // Post: Heap order property is restored between root and bottom { int maxChild ; int rightChild ; int leftChild ; leftChild = root * ; rightChild = root * ; 40 ReheapDown

if ( leftChild <= bottom )// ReheapDown continued { if ( leftChild == bottom ) //left child is the only child maxChild = leftChld ; else { if (elements [ leftChild ] <= elements [ rightChild ] ) maxChild = rightChild ; else maxChild = leftChild ; } if ( elements [ root ] < elements [ maxChild ] ) { Swap ( elements [ root ], elements [ maxChild ] ) ; ReheapDown ( maxChild, bottom ) ; } 41

42 ReHeapUp l This function is converse of ReHeapDown l It takes a leaf node that violates the order property and moves it up until its correct position is found l Each node’s value should be compared to the value of its parent and then it should be moved up if parent is smaller

// IMPLEMENTATIONcontinued void HeapType::ReheapUp ( int root, int top ) // Pre: root is the index of the node that may violate the heap // order property. The order property is satisfied from top to // next-to-last node. // Post: Heap order property is restored between root and top //Comment: The parameters passed to this function are now correct { int parent ; if ( root > top ) //If we have not reached top yet { parent = ( root - 1 ) / 2; if ( elements [ parent ] < elements [ root ] ) { Swap ( elements [ parent ], elements [ root ] ) ; ReheapUp ( parent,top ) ; //climb up } 43

44 Priority Queue A priority queue is an ADT with the property that only the highest-priority element can be accessed at any time. It can be implemented if we use a heap to enqueue and dequeue the elements Dequeuing is simple; remove the top element and use re-heapdown to correct the order Enqueueing involves adding an element at the bottom and then pushing it up to its proper location using reheapup

ADT Priority Queue Operations Transformers n MakeEmpty n Enqueue n Dequeue Observers n IsEmpty n IsFull change state observe state 45

// CLASS PQTYPE DEFINITION AND MEMBER FUNCTIONS // class PQType { public: PQType( int ); ~PQType ( ); void MakeEmpty( ); bool IsEmpty( ) const; bool IsFull( ) const; void Enqueue( int item ); void Dequeue( int& item ); private: int numItems; HeapType items; int maxItems; }; 46

PQType ~PQType Enqueue Dequeue. class PQType [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] Private Data: numItems 3 maxItems 10 items.elements.numElements