Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "1 Nell Dale Chapter 9 Trees Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures."— Presentation transcript:

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

2 2 Expressions With Binary Operators l 254+324 l 712-543 l 818*23 l 945/3 l These arithmetic expressions use BINARY OPERATORS that accept two operands

3 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 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 5 A Two-Level Binary Expression ‘-’ ‘8’ ‘5’ treePtr INORDER TRAVERSAL : 8 - 5 has value 3 PREORDER TRAVERSAL: - 8 5 POSTORDER TRAVERSAL: 8 5 -

6 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 7 A Binary Expression Tree ‘*’ ‘+’ ‘4’ ‘3’ ‘2’ What value does it have? ( 4 + 2 ) * 3 = 18

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

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

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

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

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

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

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

15 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 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 6000. whichType. operand OPERAND 7

17 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;

18 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 19 class ExprTree ‘*’ ‘+’ ‘4’ ‘3’ ‘2’ ExprTree ~ExprTree Build Evaluate. private: root

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

21 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 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 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 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 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 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 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 28 Are these both heaps? C A T treePtr 50 20 18 30 10

29 29 70 60 40 30 12 810 tree Is this a heap?

30 30 70 60 40 30 12 8 tree Where is the largest element in a heap always found?

31 31 70 0 60 1 40 3 30 4 12 2 8 5 tree We can number the nodes left to right by level this way

32 32 70 0 60 1 40 3 30 4 12 2 8 5 tree And use the numbers as array indexes to store the tree [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] 70 60 12 40 30 8 tree.nodes

33 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

34 // 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 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 36

37 37

38 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 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 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 * 2 + 1 ; rightChild = root * 2 + 2 ; 40 ReheapDown

41 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 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

43 // 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 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

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

46 // 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

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


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

Similar presentations


Ads by Google