Top Banner
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
44

Nell Dale Chapter 9 Trees Plus

Jan 21, 2016

Download

Documents

hawa

C++ Plus Data Structures. Nell Dale Chapter 9 Trees Plus Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus. A Binary Expression Tree is. A special kind of binary tree in which: 1. Each leaf node contains a single operand, - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Nell Dale Chapter 9 Trees Plus

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

Page 2: Nell Dale Chapter 9 Trees Plus

2

A special kind of binary tree in which:

1. Each leaf node contains a single operand,

2. Each nonleaf 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 3: Nell Dale Chapter 9 Trees Plus

3

A Two-Level Binary Expression

‘-’

‘8’ ‘5’

treePtr

INORDER TRAVERSAL: 8 - 5 has value 3

PREORDER TRAVERSAL: - 8 5

POSTORDER TRAVERSAL: 8 5 -

Page 4: Nell Dale Chapter 9 Trees Plus

4

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 5: Nell Dale Chapter 9 Trees Plus

5

A Binary Expression Tree

‘*’

‘+’

‘4’

‘3’

‘2’

What value does it have?

( 4 + 2 ) * 3 = 18

Page 6: Nell Dale Chapter 9 Trees Plus

6

A Binary Expression Tree

‘*’

‘+’

‘4’

‘3’

‘2’

What infix, prefix, postfix expressions does it represent?

Page 7: Nell Dale Chapter 9 Trees Plus

7

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 8: Nell Dale Chapter 9 Trees Plus

8

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

‘/’

‘+’

‘A’ ‘H’

‘-’

‘M’ ‘Y’

tree

Print left subtree first Print right subtree last

Print second

Page 9: Nell Dale Chapter 9 Trees Plus

9

Preorder Traversal: / + A H - M Y

‘/’

‘+’

‘A’ ‘H’

‘-’

‘M’ ‘Y’

tree

Print left subtree second Print right subtree last

Print first

Page 10: Nell Dale Chapter 9 Trees Plus

10

‘/’

‘+’

‘A’ ‘H’

‘-’

‘M’ ‘Y’

tree

Print left subtree first Print right subtree second

Print last

Postorder Traversal: A H + M Y - /

Page 11: Nell Dale Chapter 9 Trees Plus

11

Evaluate this binary expression tree

‘*’

‘-’

‘8’ ‘5’

What infix, prefix, postfix expressions does it represent?

‘/’

‘+’

‘4’

‘3’

‘2’

Page 12: Nell Dale Chapter 9 Trees Plus

12

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 13: Nell Dale Chapter 9 Trees Plus

13

ExprTreeNode (Lab 11)

class ExprTreeNode { private: ExprTreeNode (char elem, ExprTreeNode *leftPtr, ExprTreeNode *rightPtr); // Constructor

char element; // Expression tree element ExprTreeNode *left, // Pointer to the left child *right; // Pointer to the right child friend class Exprtree;};

. left . element . right

NULL 6000*

Page 14: Nell Dale Chapter 9 Trees Plus

14

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 15: Nell Dale Chapter 9 Trees Plus

15

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 16: Nell Dale Chapter 9 Trees Plus

16

Function Eval()

• Definition: Evaluates the expression represented by the binary tree.

• Size: The number of nodes in the tree.

• Base Case: If the content of the node is an operand, Func_value = the value of the operand.

• General Case: If the content of the node is an operator BinOperator,

Func_value = Eval(left subtree) BinOperator

Eval(right subtree)

Page 17: Nell Dale Chapter 9 Trees Plus

17

Eval(TreeNode * tree)

Algorithm:

IF Info(tree) is an operandReturn Info(tree)

ELSE SWITCH(Info(tree)) case + :Return Eval(Left(tree)) + Eval(Right(tree)) case - : Return Eval(Left(tree)) - Eval(Right(tree)) case * : Return Eval(Left(tree)) * Eval(Right(tree)) case / : Return Eval(Left(tree)) / Eval(Right(tree))

Page 18: Nell Dale Chapter 9 Trees Plus

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

19

class ExprTree

‘*’

‘+’

‘4’

‘3’

‘2’

ExprTree

~ExprTree

Build

Evaluate . . .

private:

root

Page 20: Nell Dale Chapter 9 Trees Plus

20

A Nonlinked Representation ofBinary Trees

Store a binary tree in an array in such a way that the parent-child relationships are not lost

Page 21: Nell Dale Chapter 9 Trees Plus

21

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 22: Nell Dale Chapter 9 Trees Plus

22

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.

SHAPE OF A COMPLETE BINARY TREE

Page 23: Nell Dale Chapter 9 Trees Plus

23

What is a Heap?

A heap is a binary tree 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.

Page 24: Nell Dale Chapter 9 Trees Plus

24

Are these both heaps?

C

A T

treePtr

50

20

18

30

10

Page 25: Nell Dale Chapter 9 Trees Plus

25

70

60

40 30

12

8 10

tree

Is this a heap?

Page 26: Nell Dale Chapter 9 Trees Plus

26

70

60

40 30

12

8

tree

Where is the largest element in a heap always found?

“maximum heap”

Page 27: Nell Dale Chapter 9 Trees Plus

27

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 28: Nell Dale Chapter 9 Trees Plus

28

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 29: Nell Dale Chapter 9 Trees Plus

29

Parent-Child Relationship?

tree.nodes[index]:left child: tree.nodes[index*2 + 1]right child: tree.nodes[index*2 + 2]parent: tree.nodes[(index-1) / 2]

Leaf nodes: tree.nodes[numElements / 2]…tree.nodes[numElements - 1]

Page 30: Nell Dale Chapter 9 Trees Plus

30

An application …

Fast access to the largest (or highest-priority) element in the structure:

- remove the element with the largest value from a heap …

Page 31: Nell Dale Chapter 9 Trees Plus

// HEAP SPECIFICATION

// Assumes ItemType is either a built-in simple data type// or a class with overloaded realtional operators.

template< class ItemType >struct HeapType

{ void ReheapDown ( int root , int bottom ) ;

void ReheapUp ( int root, int bottom ) ;

ItemType* elements ; // ARRAY to be allocated dynamically

int numElements ;

};

31

Page 32: Nell Dale Chapter 9 Trees Plus

32

ReheapDown(root, bottom)

IF elements[root] is not a leaf

Set maxChild to index of child with larger value

IF elements[root] < elements[maxChild])

Swap(elements[root], elements[maxChild]) ReheapDown(maxChild, bottom)

Page 33: Nell Dale Chapter 9 Trees Plus

33

// IMPLEMENTATION OF RECURSIVE HEAP MEMBER FUNCTIONS

template< class ItemType >void HeapType<ItemType>::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 ; 33

ReheapDown()

Page 34: Nell Dale Chapter 9 Trees Plus

if ( leftChild <= bottom ) // ReheapDown continued {

if ( leftChild == bottom ) 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 ) ;}

}}

34

Page 35: Nell Dale Chapter 9 Trees Plus

// IMPLEMENTATION continued

template< class ItemType >void HeapType<ItemType>::ReheapUp ( int root, int bottom )

// Pre: bottom is the index of the node that may violate the heap // order property. The order property is satisfied from root to // next-to-last node.// Post: Heap order property is restored between root and bottom

{ int parent ;

if ( bottom > root ) {

parent = ( bottom - 1 ) / 2;if ( elements [ parent ] < elements [ bottom ] ){

Swap ( elements [ parent ], elements [ bottom ] ) ;ReheapUp ( root, parent ) ;

} }} 35

Page 36: Nell Dale Chapter 9 Trees Plus

36

Priority Queue

A priority queue is an ADT with the property that only the highest-priority element can be accessed at any time.

Page 37: Nell Dale Chapter 9 Trees Plus

Priority Queue ADT Specification

Structure: The Priority Queue is arranged to support

access to the highest priority item

Operations: MakeEmpty Boolean IsEmpty Boolean IsFull Enqueue(ItemType newItem) Dequeue(ItemType& item)

37

Page 38: Nell Dale Chapter 9 Trees Plus

ADT Priority Queue Operations

Transformers MakeEmpty Enqueue Dequeue

Observers IsEmpty IsFull

change state

observe state

38

Page 39: Nell Dale Chapter 9 Trees Plus

Dequeue(ItemType& item)

Function: Removes element with highest priority and returns it

in item.

Precondition: Queue is not empty.

Postcondition:Highest priority element has been removed from

queue.Item is a copy of removed element.

39

Page 40: Nell Dale Chapter 9 Trees Plus

// CLASS PQTYPE DEFINITION AND MEMBER FUNCTIONS

//--------------------------------------------------------

#include "bool.h"#include "ItemType.h" // for ItemType

template<class ItemType>

class PQType {

public:

PQType( int );

~PQType ( );

void MakeEmpty( );

bool IsEmpty( ) const;

bool IsFull( ) const;

void Enqueue( ItemType item );

void Dequeue( ItemType& item );

private:

int numItems;

HeapType<ItemType> items;

int maxItems;

}; 40

Page 41: Nell Dale Chapter 9 Trees Plus

PQType

~PQType

Enqueue

Dequeue . . .

class PQType<char>

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

‘X’ ‘C’ ‘J’

Private Data:

numItems

3

maxItems

10

items

.elements .numElements

Page 42: Nell Dale Chapter 9 Trees Plus

Implementation Level

Algorithm:

Dequeue(): O(log2N) Set item to root element from queue Move last leaf element into root position Decrement numItems items.ReheapDown(0, numItems-1)

Enqueue(): O(log2N) Increment numItems Put newItem in next available position items.ReheapUp(0, numItems-1)

42

Page 43: Nell Dale Chapter 9 Trees Plus

Comparison of Priority Queue Implementations

43

Enqueue Dequeue

Heap O(log2N) O(log2N)

Linked List O(N) O(1)

Binary Search Tree

Balanced O(log2N) O(log2N)

Skewed O(N) O(N)

Trade-offs: read Text page 548

Page 44: Nell Dale Chapter 9 Trees Plus

44

End