chapter 19: binary trees java programming: program design including data structures program design...

57
Chapter 19: Binary Trees Chapter 19: Binary Trees Java Programming: Java Programming: Program Design Including Data Program Design Including Data Structures Structures

Upload: clifton-knight

Post on 03-Jan-2016

467 views

Category:

Documents


6 download

TRANSCRIPT

Page 1: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Chapter 19: Binary TreesChapter 19: Binary Trees

Java Programming: Java Programming:

Program Design Including Data Program Design Including Data StructuresStructures

Page 2: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 2

Chapter Objectives

Learn about binary trees Explore various binary tree traversal algorithms Learn how to organize data in a binary search tree Discover how to insert and delete items in a binary

search tree

Page 3: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 3

Binary Trees

A binary tree, T, is either empty or T has a special node called the root node T has two sets of nodes, LT and RT, called the left

subtree and right subtree LT and RT are binary trees

A binary tree can be shown pictorially

Page 4: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 4

Binary Trees (continued)

Figure 19-1 Binary tree

Page 5: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 5

Binary Trees (continued)

Figure 19-6 Various binary trees with three nodes

Page 6: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 6

Binary Trees (continued) You can write a class that represents each node in a

binary tree Called BinaryTreeNode

Instance variables of the class BinaryTreeNode info: stores the information part of the node lLink: points to the root node of the left subtree rLink: points to the root node of the right subtree

Page 7: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 7

Binary Trees (continued)

Figure 19-7 UML class diagram of the class BinaryTreeNode and the outer-inner class relationship

Page 8: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 8

Binary Trees (continued)

Figure 19-8 Binary tree

Page 9: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 9

Binary Trees (continued)

A leaf is a node in a tree with no children Let U and V be two nodes in a binary tree

U is called the parent of V if there is a branch from U to V

A path from a node X to a node Y is a sequence of nodes X0, X1, ..., Xn such that:

X = X0,Xn = Y

Xi-1 is the parent of Xi for all i = 1, 2, ..., n

Page 10: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 10

Binary Trees (continued)

Length of a path The number of branches on that path

Level of a node The number of branches on the path from the root to

the node Height of a binary tree

The number of nodes on the longest path from the root to a leaf

Page 11: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 11

Binary Trees (continued)

Method heightprivate int height(BinaryTreeNode<T> p)

{

if (p == null)

return 0;

else

return 1 + Math.max(height(p.lLink), height(p.rLink));

}

Page 12: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 12

Copy Tree

Method copyTreeprivate BinaryTreeNode<T> copyTree

(BinaryTreeNode<T> otherTreeRoot)

{

BinaryTreeNode<T> temp;

if (otherTreeRoot == null)

temp = null;

else

{

temp = (BinaryTreeNode<T>) otherTreeRoot.clone();

temp.lLink = copyTree(otherTreeRoot.lLink);

temp.rLink = copyTree(otherTreeRoot.rLink);

}

return temp;

}//end copyTree

Page 13: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 13

Binary Tree Traversal

Item insertion, deletion, and lookup operations require that the binary tree be traversed

Commonly used traversals Inorder traversal Preorder traversal Postorder traversal

Page 14: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 14

Inorder Traversal

Binary tree is traversed as follows: Traverse left subtree Visit node Traverse right subtree

Page 15: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 15

Inorder Traversal (continued)

Method inOrderprivate void inorder(BinaryTreeNode<T> p)

{

if (p != null)

{

inorder(p.lLink);

System.out.print(p + “ “);

inorder(p.rLink);

}

}

Page 16: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 16

Preorder Traversal

Binary tree is traversed as follows: Visit node Traverse left subtree Traverse right subtree

Page 17: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 17

Preorder Traversal (continued)

Method preOrderprivate void preorder(BinaryTreeNode<T> p)

{

if (p != null)

{

System.out.print(p + “ “);

preorder(p.lLink);

preorder(p.rLink);

}

}

Page 18: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 18

Postorder Traversal

Binary tree is traversed as follows: Traverse left subtree Traverse right subtree Visit node

Page 19: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 19

Postorder Traversal (continued)

Method postOrderprivate void postorder(BinaryTreeNode<T> p)

{

if (p != null)

{

postorder(p.lLink);

postorder(p.rLink);

System.out.print(p + “ “);

}

}

Page 20: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 20

Implementing Binary Trees

Figure 19-11 UML class diagram of the interface BinaryTreeADT

Page 21: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 21

Implementing Binary Trees (continued)

Figure 19-12 UML class diagram of the class BinaryTree

Page 22: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 22

Implementing Binary Trees (continued)

Method clonepublic Object clone()

{

BinaryTree<T> copy = null;

try

{

copy = (BinaryTree<T>) super.clone();

}

catch (CloneNotSupportedException e)

{

return null;

}

if (root != null)

copy.root = copyTree(root);

return copy;

}

Page 23: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 23

Binary Search Trees

To search for an item in a normal binary tree, you must traverse entire tree until item is found Search process will be very slow Similar to searching in an arbitrary linked list

Binary search tree Data in each node is

Larger than the data in its left child Smaller than the data in its right child

Page 24: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 24

Binary Search Trees (continued)

Figure 19-14 Binary search tree

Page 25: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 25

Binary Search Trees (continued)

Figure 19-15 UML class diagram of the class BinarySearchTree and the inheritance hierarchy

Page 26: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 26

Search

Searches tree for a given item General steps

Compare item with info in root node If they are the same, stop the search

If item is smaller than info in root node Follow link to left subtree

Otherwise Follow link to right subtree

Page 27: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 27

Insert

Inserts a new item into a binary search tree General steps

Search tree and find the place where new item is to be inserted Search algorithm is similar to method search

Insert new item Duplicate items are not allowed

Page 28: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 28

Delete

Deletes item from a binary search tree After deleting items, resulting tree must be a binary

search tree General steps

Search the tree for the item to be deleted Searching algorithm is similar to method search

Delete item

Page 29: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 29

Delete (continued)

Delete operation has four cases Case 1: Node to be deleted is a leaf Case 2: Node to be deleted has no left subtree Case 3: Node to be deleted has no right subtree Case 4: Node to be deleted has nonempty left and

right subtrees search left subtree of the node to be deleted to find its immediate predecessor

Page 30: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 30

Binary Search Tree: Analysis

Performance depends on shape of the tree If tree shape is linear, performance is the same as for

a linked list Average number of nodes visited

1.39log2n = O(log2n)

Average number of key comparisons

2.77log2n = O(log2n)

Page 31: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 31

Nonrecursive Binary Tree Traversal Algorithms

Traversal algorithms Inorder Preorder Postorder

Page 32: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 32

Nonrecursive Inorder Traversal

Method nonRecursiveInTraversalpublic void nonRecursiveInTraversal()

{

LinkedStackClass<BinaryTreeNode<T> > stack

= new LinkedStackClass<BinaryTreeNode<T> >();

BinaryTreeNode<T> current;

current = root;

while ((current != null) || (!stack.isEmptyStack()))

if (current != null)

{

stack.push(current);

current = current.lLink;

}

Page 33: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 33

Nonrecursive Inorder Traversal (continued)

else

{

current = (BinaryTreeNode<T>) stack.peek();

stack.pop();

System.out.print(current.info + “ “);

current = current.rLink;

}

System.out.println();

}

Page 34: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 34

Nonrecursive Preorder Traversal

General algorithmcreate stack

current = root;

while (current is not null or stack is nonempty)

if (current is not null)

{

visit current;

push current onto stack;

current = current.lLink;

}

else

{

pop stack into current;

current = current.rLink; //prepare to visit right subtree

}

Page 35: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 35

Nonrecursive Postorder Traversal

General algorithm Mark left subtree of node as visited Visit left subtree and return to node Mark right subtree of node as visited Visit right subtree and return to node Visit node

Page 36: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 36

An Iterator to a Binary Tree

You can create an iterator for a binary tree Iterator can traverse tree using

Inorder traversal Preorder traversal Postorder traversal

Page 37: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 37

AVL (Height-Balanced) Trees Search performance depends on shape of the tree

You want the tree to be balanced AVL (height-balanced) tree

Resulting binary search tree is nearly balanced Perfectly balanced binary search tree

Heights of the left and right subtrees are equal Left and right subtrees are perfectly balanced binary

trees

Page 38: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 38

AVL (Height-Balanced) Trees(continued)

Figure 19-24 Perfectly balanced binary tree

Page 39: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 39

AVL (Height-Balanced) Trees (continued)

AVL tree: A binary search tree where Heights of left and right subtrees differs by at most 1 Left and right subtrees are AVL trees

Balance factor Difference between height of right subtree and height

of left subtree

Page 40: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 40

AVL (Height-Balanced) Trees (continued)

Figure 19-25 Perfectly balanced binary tree

Page 41: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 41

Insertion into AVL Trees

General steps Search AVL tree to find insertion point Insert new item

Duplicate items are not allowed Rebalance tree (if needed)

Page 42: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 42

Insertion into AVL Trees (continued)

Figure 19-27 AVL tree before inserting 90

Page 43: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 43

Insertion into AVL Trees (continued)

Figure 19-28 Binary search tree of Figure 19-27 after inserting 90; nodes other than 90 show their balance factors before insertion

Page 44: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 44

Insertion into AVL Trees (continued)

Figure 19-29 AVL tree of Figure 19-27 after inserting 90 and adjusting the balance factors

Page 45: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 45

AVL Tree Rotations

Reconstruction procedure Types of rotations

Left rotation Nodes from right subtree move to left subtree Root of right subtree becomes root of reconstructed

subtree Right rotation

Nodes from left subtree move to right subtree Root of left subtree becomes root of reconstructed

subtree

Page 46: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 46

AVL Tree Rotations (continued)

Figure 19-39 Left rotation at a

Page 47: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 47

AVL Tree Rotations (continued)

Figure 19-39 Right rotation at b

Page 48: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 48

AVL Tree Rotations (continued) Method rotateToLeftprivate AVLNode<T> rotateToLeft(AVLNode<T> root)

{

AVLNode<T> p; //reference variable to the root of the right subtree of root

if (root == null)

System.err.println(“Error in the tree.”);

else

if (root.rLink == null)

System.err.println(“Error in the tree: “

+ “No right subtree to rotate.”);

else

{

p = root.rLink;

root.rLink = p.lLink; //the left subtree of p becomes the right

//subtree of root

p.lLink = root;

root = p; //make p the new root node

}

return root;

}//end rotateToLeft

Page 49: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 49

AVL Tree Rotations (continued) Method rotateToRightprivate AVLNode<T> rotateToRight(AVLNode<T> root)

{

AVLNode<T> p; //reference variable to the root of the

//left subtree of root

if (root == null)

System.err.println(“Error in the tree.”);

else

if (root.lLink == null)

System.err.println(“Error in the tree: “

+ “No left subtree to rotate.”);

else

{

p = root.lLink;

root.lLink = p.rLink; //the right subtree of p

//becomes the left subtree of root

p.rLink = root;

root = p; //make p the new root node

}

return root;

}//end rotateToRight

Page 50: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 50

AVL Tree Rotations (continued)

Figure 19-44 AVL tree after inserting 40

Figure 19-45 AVL tree after inserting 30

Page 51: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 51

AVL Tree Rotations (continued)

Figure 19-46 AVL tree after inserting 20

Page 52: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 52

AVL Tree Rotations (continued)

Figure 19-46 AVL tree after inserting 25

Page 53: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 53

Deletion from AVL Trees General steps

Find node to be deleted Delete node

Four cases arise: Node to be deleted is a leaf Node to be deleted has no right child Node to be deleted has no left child Node to be deleted has both children

Page 54: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 54

Height of AVL tree with n nodes (worst case)

1.44log2n = O(log2n)

Time to manipulate an AVL tree in the worst case is no more than 44% of optimum time

Average search time of an AVL tree is about 4% more than the optimum

Analysis: AVL Trees

Page 55: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 55

Programming Example: Video Store (Revisited)

Program in Chapter 16 used a linked list to keep track of video inventory Search could be time consuming

Modify program to use a binary tree instead Insertion and deletion in a binary search tree is faster

than in a linked list

Page 56: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 56

Chapter Summary

Binary trees Every node has only two children

Left subtree Right subtree

Binary tree traversal Inorder Preorder Postorder

Page 57: Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures

Java Programming: Program Design Including Data Structures 57

Chapter Summary (continued) Binary search trees

Each node is greater than elements in its left subtree and less than elements in its right subtree

AVL (height-balanced) trees Binary search tree Heights of left and right subtrees differs by at most 1 Left and right subtrees of the root node are AVL trees