chapter 8 binary search trees. 2 goals define and use the following terminology: binary tree root...

77
Chapter 8 Binary Search Trees

Upload: marjorie-porter

Post on 04-Jan-2016

221 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

Chapter 8

Binary Search Trees

Page 2: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

2

Goals

• Define and use the following terminology: binary tree root

descendant subtree binary search tree parent level

ancestor child height

• Define a binary search tree at the logical level

• Show what a binary search tree would look like after a series of insertions and deletions

Page 3: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

3

Goals

• Implement the following binary search tree algorithms in C++

Inserting an element

Deleting an element

Retrieving an element

Modifying an element

Copying a tree

Traversing a tree in preorder, inorder, postorder

Page 4: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

4

Goals

• Discuss the Big-O efficiency of a given binary search tree operation

• Describe an algorithm for balancing a binary search tree

• Show how a binary tree can be represented in an array, with implicit positional links between the elements

• Define the terms full binary tree and complete binary tree

Page 5: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

5

Owner Jake

Manager Chef Brad Carol

Waitress Waiter Cook Helper Joyce Chris Max Len

Trees

Jake’s Pizza Shop

Page 6: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

6

Owner Jake

Manager Chef Brad Carol

Waitress Waiter Cook Helper Joyce Chris Max Len

ROOT NODE

Trees

Page 7: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

7

Owner Jake

Manager Chef Brad Carol

Waitress Waiter Cook Helper Joyce Chris Max Len

LEAF NODES

Trees

Page 8: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

8

Owner Jake

Manager Chef Brad Carol

Waitress Waiter Cook Helper Joyce Chris Max Len

LEVEL 0

Trees

Page 9: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

9

Owner Jake

Manager Chef Brad Carol

Waitress Waiter Cook Helper Joyce Chris Max Len

LEVEL 1

Trees

Page 10: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

10

Owner Jake

Manager Chef Brad Carol

Waitress Waiter Cook Helper Joyce Chris Max Len

LEVEL 2

Trees

Page 11: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

11

Owner Jake

Manager Chef Brad Carol

Waitress Waiter Cook Helper Joyce Chris Max Len

LEFT SUBTREE OF ROOT NODE

Trees

Page 12: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

12

Owner Jake

Manager Chef Brad Carol

Waitress Waiter Cook Helper Joyce Chris Max Len

RIGHT SUBTREE OF ROOT NODE

Trees

Page 13: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

13

Trees

Binary Tree

A structure with a unique starting node (the root), in which each node is capable of having two child nodes and a unique path exists from the root to every other node

Root

The top node of a tree structure; a node with no parent

Leaf Node

A tree node that has no children

Page 14: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

14

Trees

LevelDistance ofa node fromthe root

HeightThe maximumlevel

Page 15: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

15

Trees

Why isthis not atree

?

Page 16: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

16

Trees

Q

V

T

K S

A E

L

How many leaf nodes?

Page 17: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

17

Trees

Q

V

T

K S

A E

L

Q has how manydescendant?

Page 18: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

18

Trees

Q

V

T

K S

A E

L

S has how manyancestors?

Page 19: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

19

Trees

How many different binary trees can be madefrom 2 nodes? 4 nodes? 6 nodes?

Page 20: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

20

Binary Search Trees

Binary Search Trees

A binary tree in which the key value in any node is greater than the key value in the left child and any of its children and less than the key value in the right child and any of its children

A BST is a binary tree with the search property

Page 21: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

21

Binary Search Trees

Eachnode is

theroot of asubtree

Page 22: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

22

Recursive Implementation

Page 23: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

23

Recursive Count

Let’s start by counting the number of nodes in

a tree

Size?

Base cases(s)?

General case(s)?

Page 24: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

24

Recursive Count

Count (Version 1)

if (Left(tree) is NULL) AND (Right(tree) is NULL)

return 1

else

return Count (Left(tree)) + Count(Right(tree)) + 1

Apply tothese trees

Page 25: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

25

Recursive Count

Count (Version 2)if (left(tree) is NULL) AND (Right(tree) is NULL)

return 1else if (Left(tree) is NULL)

return Count(Right(tree)) + 1else if (Right(tree) is NULL)

return Count(Left(tree)) + 1else return Count(Left(tree)) + Count(Right(tree)) + 1

Apply to an empty tree

Page 26: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

26

Recursive Count

Count (Version 3)if (tree is NULL)

// Version 2

Stop

Count (Version 4)if (tree is NULL)

return 0else

return Count(Left(tree)) + Count(Right(tree)) + 1

Page 27: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

27

Recursive Count

int TreeType() const{ return Count(root);)int Count(TreeNode* tree){ if (tree == NULL) return 0 else return Count(tree->left) + Count(tree->right) + 1;}

Why do we need two functions?

Page 28: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

28

Recursive Search

‘J’

‘E’

‘A’ ‘H’

‘T’

‘M’

‘K’

‘V’

‘P’ ‘Z’‘D’

‘Q’‘L’‘B’

‘S’Are ‘D’, ‘Q’, and ‘N’ in the tree?

Page 29: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

29

Recursive Search

Retrieve(tree, item, found)

Size?

Base case(s)?

General case(s)?

Page 30: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

30

Recursive Search

void Retrieve(TreeNode* tree, ItemType& item,

bool& found){ if (tree == NULL) found = false; else if (item < tree->info) Retrieve(tree->left, item, found); else if (item > tree->info) Retrieve(tree->right, item, found); else { item = tree->info; found = true; }}

Page 31: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

31

Shape depends on the order of item insertion

Insert the elements ‘J’ ‘E’ ‘F’ ‘T’ ‘A’ in that order

The first value inserted is always put in the root

Shape of BST

‘J’

Page 32: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

32

Thereafter, each value to be inserted

compares itself to the value in the root node

moves left it is less or

moves right if it is greater

When does the process stop?

Shape of BST

‘J’

‘E’

Page 33: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

33

Trace path to insert ‘F’

Shape of BST

‘J’

‘E’

‘F’

Page 34: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

34

Trace path to insert ‘T’

Shape of BST

‘J’

‘E’

‘F’

‘T’

Page 35: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

35

Trace path to insert ‘A’

Shape of BST

‘J’

‘E’

‘F’

‘T’

‘A’

Page 36: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

36

Now build tree by inserting ‘A’ ‘E’ ‘F’ ‘J’ ‘T’ in that order

Shape of BST

And the moral is?

Page 37: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

37

Recursive Insertion

Insert an item into a tree

Where does each new node get inserted?

Insert(tree, item)if (tree is NULL)

Get a new nodeSet right and left to NULLSet info to item

Page 38: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

38

Recursive Insertion

Page 39: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

39

Recursive Insertion

Page 40: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

40

Recursive Insertion

How mustthe tree

bepassed?

Page 41: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

41

Recursive Insertionvoid Insert(TreeNode*& tree, ItemType item){ if (tree == NULL) {// Insertion place found. tree = new TreeNode; tree->right = NULL; tree->left = NULL; tree->info = item; } else if (item < tree->info) Insert(tree->left, item); else Insert(tree->right, item); }

Page 42: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

42

Recursive DeletionDelete ‘Z’

Page 43: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

43

Recursive Deletion

Delete ‘R’

Page 44: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

44

Recursive Deletion

Delete ‘Q’

Page 45: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

45

Recursive Deletion

Can you summarize the three deletion cases?

Page 46: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

46

Recursive Deletion

DeleteItem(tree, item)

if (Left(tree) is NULL) AND (Right(tree) is NULL)

Set tree to NULL

else if Left(tree) is NULL

Set tree to Right(tree)

else if Right(tree) is NULL

Set tree to Left(tree)

else

Find predecessor

Set Info(tree) to Info(predecessor)

Delete predecessor

Page 47: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

47

Recursive Deletion

void Delete(TreeNode*& tree, ItemType item){ if (item < tree->info) Delete(tree->left, item); else if (item > tree->info) Delete(tree->right, item); else DeleteNode(tree); // Node found}

Page 48: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

48

Recursive Deletionvoid DeleteNode(TreeNode*& tree){ ItemType data; TreeNode* tempPtr; tempPtr = tree; if (tree->left == NULL) { tree = tree->right; delete tempPtr; } else if (tree->right == NULL){ tree = tree->left; delete tempPtr;} els{ GetPredecessor(tree->left, data); tree->info = data; Delete(tree->left, data);}}

Page 49: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

49

Recursive Deletion

void GetPredecessor(TreeNode* tree, ItemType& data)

{ while (tree->right != NULL) tree = tree->right; data = tree->info;}

Why is the code not recursive?

Page 50: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

50

Recursive Deletion

Page 51: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

51

Printing the Tree

Apply same algorithm to each tree

What is the order of the output?

Page 52: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

52

Printing the Tree

PrintTree operation

Size?

Base case(s)?

General case(s)?

Page 53: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

53

Printing the Tree

void PrintTree(TreeNode* tree,

std::ofstream& outFile)

{

if (tree != NULL)

{

PrintTree(tree->left, outFile);

outFile << tree->info;

PrintTree(tree->right, outFile);

}

}

Is thatall

thereis?

Page 54: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

54

A QuestionDo we need a destructor?

Page 55: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

55

Copying a Tree

CopyTree(copy, originalTree)

if (originalTree is NULL)

Set copy to NULL

else

Set copy to new node

Set Info(copy) to Info(originalTree)

CopyTree(Left(copy), Left(originalTree))

CopyTree(Right(copy), Right(originalTree))

How must copy be passed?How must originalTree be passed?

Page 56: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

56

Copying a Treevoid CopyTree(TreeNode*& copy, const TreeNode* originalTree){ if (originalTree == NULL) copy = NULL; else { copy = new TreeNode; copy->info = originalTree->info; CopyTree(copy->left, originalTree->left); CopyTree(copy->right, originalTree->right); }}

Page 57: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

57

Traversals

Inorder(tree)if tree is not NULL

Inorder(Left(tree))Visit Info(tree)Inorder(Right(tree))

PostOrder(tree)if tree is not NULL

Postorder(Left(tree))Postorder(Right(tree))Visit Info(tree)

 

PreOrder(tree)if tree is not NULL

Visit Info(tree)Preorder(Left(tree))

Preorder(Right(tree))

alphabetic order

destructor (why?)

expression evaluation

Page 58: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

58

Traversals

Each nodeis visited

three times

Page 59: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

59

Traversals

Page 60: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

60

Iterator

Approach The client program passes a parameter to ResetTree

and GetNextItem indicating which of the three traversals to use

ResetTree generates a queues of node contents in the indicated order

GetNextItem processes the node contents from the appropriate queue: inQue, preQue, postQue

Page 61: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

61

Iteratorvoid TreeType::ResetTree(OrderType order)// Calls function to create a queue of the tree // elements in the desired order.{ switch (order) { case PRE_ORDER : PreOrder(root, preQue); break; case IN_ORDER : InOrder(root, inQue); break; case POST_ORDER: PostOrder(root, postQue); break; }}

Page 62: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

62

void TreeType::GetNextItem(ItemType& item, OrderType order,bool& finished){ finished = false; switch (order) { case PRE_ORDER : preQue.Dequeue(item); if (preQue.IsEmpty()) finished = true; break; case IN_ORDER : inQue.Dequeue(item); if (inQue.IsEmpty()) finished = true; break; case POST_ORDER: postQue.Dequeue(item); if (postQue.IsEmpty()) finished = true; break; }}

Iterator

Page 63: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

63

Iterative Versions

FindNode(tree, item, nodePtr, parentPtr)Set nodePtr to treeSet parentPtr to NULLSet found to false while more elements to search AND NOT found

if item < Info(nodePtr)Set parentPtr to nodePtrSet nodePtr to Left(nodePtr)

else if item > Info(nodePtr)Set parentPtr to nodePtrSet nodePtr to Right(nodePtr)

elseSet found to true

Page 64: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

64

Iterative Versions

InsertItem

Create a node to contain the new item

Find the insertion place

Attach new node

Find the insertion place

FindNode(tree, item, nodePtr, parentPtr);

Page 65: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

65

Iterative Versions

Insert 13

Page 66: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

66

Iterative Versions

Page 67: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

67

Iterative Versions

AttachNewNode

if item < Info(parentPtr)

Set Left(parentPtr) to newNode

else

Set Right(parentPtr) to newNode

See aproblem

?

Page 68: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

68

Iterative Version

AttachNewNode(revised)

if parentPtr equals NULL

Set tree to newNode

else if item < Info(parentPtr)

Set Left(parentPtr) to newNode

else

Set Right(parentPtr) to newNode

Page 69: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

69

Iterative Version

void TreeType::DeleteItem(ItemType item)

{ TreeNode* nodePtr; TreeNode* parentPtr; FindNode(root, item, nodePtr,

parentPtr); if (nodePtr == root) DeleteNode(root); else if (parentPtr->left == nodePtr) DeleteNode(parentPtr->left); else DeleteNode(parentPtr->right);}

Why not parentPtr?

Why not nodePtr?

Page 70: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

70

Iterative Version

parentPtr and nodePtr are external; parentPtr->left is internal

Page 71: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

71

Recursion VS Iteration

Compare versions of Tree algorithms

Is the depth of recursion relatively shallow?

Is the recursive solution shorter or cleaner?

Is the recursive version much less efficient?

Page 72: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

72

Nonlinked Representation

What is the mapping into the index?

Page 73: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

73

Nonlinked Representation

For any node tree.nodes[index]its left child is in tree.nodes[index*2 + 1]right child is in tree.nodes[index*2 + 2]its parent is in tree.nodes[(index - 1)/2]

Can you determine which nodes are leaf nodes?

Page 74: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

74

Nonlinked Representation

Full Binary Tree

A binary tree in which all of the leaves are on the same level and every nonleaf node has two children

Page 75: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

75

Nonlinked Representation

Complete Binary Tree

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

Page 76: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

76

Nonlinked Representation

Page 77: Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor

77

Nonlinked Representation

A techniquefor storing

a non-complete

tree