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

Post on 20-Dec-2015

219 Views

Category:

Documents

2 Downloads

Preview:

Click to see full reader

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

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

BINARY OPERATORS that accept two operands

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

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: 8 - 5 has value 3

PREORDER TRAVERSAL: - 8 5

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?

( 4 + 2 ) * 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: ( ( 4 + 2 ) * 3 )

Prefix: * + 4 2 3

Postfix: 4 2 + 3 * has operators in order used

10

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

‘/’

‘+’

‘A’ ‘H’

‘-’

‘M’ ‘Y’

tree

Print left subtree first Print right subtree last

Print second

11

Preorder Traversal: / + A H - M Y

‘/’

‘+’

‘A’ ‘H’

‘-’

‘M’ ‘Y’

tree

Print left subtree second Print right subtree last

Print first

12

‘/’

‘+’

‘A’ ‘H’

‘-’

‘M’ ‘Y’

tree

Print left subtree first Print 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: ( ( 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

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 6000

. whichType . operand

OPERAND 7

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;

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

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

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

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:

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

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

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?

28

Are these both heaps?

C

A T

treePtr

50

20

18

30

10

29

70

60

40 30

12

8 10

tree

Is this a heap?

30

70

60

40 30

12

8

tree

Where is the largest element in a heap always found?

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

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

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

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

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

36

37

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

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

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

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

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

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

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

ADT Priority Queue Operations

Transformers MakeEmpty Enqueue Dequeue

Observers IsEmpty 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]

45 34 12

Private Data:

numItems

3

maxItems

10

items

.elements .numElements

top related