1 nell dale chapter 9 trees plus slides by sylvia sorkin, community college of baltimore county -...

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

Post on 20-Dec-2015

219 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: 1 Nell Dale Chapter 9 Trees 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

Page 2: 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

254+324 712-543 818*23 945/3 These arithmetic expressions use

BINARY OPERATORS that accept two operands

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

3

Evaluating Expressions With Binary Operators

(2+5)*2/3 This expression is evaluated by using

precedence rules The parenthesized expression is solved first,

then the multiplication is carried out and next the division

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

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

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

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

5

A Two-Level Binary Expression

‘-’

‘8’ ‘5’

treePtr

INORDER TRAVERSAL: 8 - 5 has value 3

PREORDER TRAVERSAL: - 8 5

POSTORDER TRAVERSAL: 8 5 -

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

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.

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

7

A Binary Expression Tree

‘*’

‘+’

‘4’

‘3’

‘2’

What value does it have?

( 4 + 2 ) * 3 = 18

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

8

A Binary Expression Tree

‘*’

‘+’

‘4’

‘3’

‘2’

What infix, prefix, postfix expressions does it represent?

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

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

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

10

Inorder Traversal: (A + H) / (M - Y)

‘/’

‘+’

‘A’ ‘H’

‘-’

‘M’ ‘Y’

tree

Print left subtree first Print right subtree last

Print second

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

11

Preorder Traversal: / + A H - M Y

‘/’

‘+’

‘A’ ‘H’

‘-’

‘M’ ‘Y’

tree

Print left subtree second Print right subtree last

Print first

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

12

‘/’

‘+’

‘A’ ‘H’

‘-’

‘M’ ‘Y’

tree

Print left subtree first Print right subtree second

Print last

Postorder Traversal: A H + M Y - /

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

13

Evaluate this binary expression tree

‘*’

‘-’

‘8’ ‘5’

What infix, prefix, postfix expressions does it represent?

‘/’

‘+’

‘4’

‘3’

‘2’

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

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’

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

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

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

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

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

17

Storing Information

treeinfo.whichtype = OPERATOR; treeinfo.operation = ‘+’; Next time, we can store an operand in

the same node by the following statements

treeinfo.whichtype = OPERAND; treeinfo.operand = 24;

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

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

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

19

class ExprTree

‘*’

‘+’

‘4’

‘3’

‘2’

ExprTree

~ExprTree

Build

Evaluate . . .

private:

root

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

20

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

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

21

Relationships

Node 0’s children are in nodes 1 and 2 Node 1’s children are in nodes 3 and 4 Node 2’s children are in nodes 5 and 6 Node n’s children are in nodes 2n+1 and 2n+2 From half point (NumElements/2) to last

element are the leaf nodes Node n’s parent is in (n-1)/2 Array implementation works well with full trees

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

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

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

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

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

24

Array Storage of non-complete trees

If some children are missing in higher levels, we store a dummy value in the array e.g. a negative number

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

25

What is a Heap?

A heap is a binary tree (not a BST) that satisfies these special SHAPE and ORDER properties:

Its shape must be a complete binary tree.

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.

This heap is different from the heap (free storage) available to programs using dynamic memory allocation

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

26

Heaps are Complete Trees

By shape, Heaps are complete binary trees Complete does not mean *full* A heap exactly follows the definition of a

complete binary tree on slide 23 A heap must be full until the second last level A heap may or may not be full on the last level 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!!

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

27

Storing Heaps into Arrays

With the above properties in mind, check the heap given in the worksheet

See how it is stored it in an array Can you verify the relationship between parents

and children? Parent of a node is (n-1)/2 Left child is 2n+1; right child is 2n+2 (if it exists) Delete node E from the heap; does it alter the

relationships?

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

28

Are these both heaps?

C

A T

treePtr

50

20

18

30

10

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

29

70

60

40 30

12

8 10

tree

Is this a heap?

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

30

70

60

40 30

12

8

tree

Where is the largest element in a heap always found?

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

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

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

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

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

33

Implementing Heap

We define the heap as a struct because mostly heaps are not used alone. They are used in combination with classes implementing other functions

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

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

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

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

35

Maintaining Heap

Maintaining Heap is not easy When we delete an element from the heap,

we have to copy a node from the bottom in its place to maintain the shape

But the heap loses its order property We must swap elements until we fix this

problem Consider the problem shown in the next slides

when the root node is deleted

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

36

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

37

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

38

ReHeapDown

We call the function ReHeapDown that pushes down the element that violates the heap order property until the problem is fixed

It is a recursive function that takes the index of the current node in violation and the index of the bottom element

The Heap is to be fixed between the current node and the bottom element

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

39

ReHeapDown

Each time ReHeapDown is called, we go down one level thus we satisfy the smaller caller criterea for recursion

There are two base cases where we stop: If elements[root] is a leaf If heap order property is satisfied

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

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

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

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

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

42

ReHeapUp

This function is converse of ReHeapDown

It takes a leaf node that violates the order property and moves it up until its correct position is found

Each node’s value should be compared to the value of its parent and then it should be moved up if parent is smaller

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

// IMPLEMENTATION continued

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

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

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 orderEnqueueing involves adding an element at the bottom and then pushing it up to its proper location using reheapup

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

ADT Priority Queue Operations

Transformers MakeEmpty Enqueue Dequeue

Observers IsEmpty IsFull

change state

observe state

45

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

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

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

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