Download presentation
Presentation is loading. Please wait.
Published byClifton Knight Modified over 9 years ago
1
Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures
2
Java Programming: Program Design Including Data Structures2 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
3
Java Programming: Program Design Including Data Structures3 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, L T and R T, called the left subtree and right subtree L T and R T are binary trees A binary tree can be shown pictorially
4
Java Programming: Program Design Including Data Structures4 Binary Trees (continued) Figure 19-1 Binary tree
5
Java Programming: Program Design Including Data Structures5 Binary Trees (continued) Figure 19-6 Various binary trees with three nodes
6
Java Programming: Program Design Including Data Structures6 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
7
Java Programming: Program Design Including Data Structures7 Binary Trees (continued) Figure 19-7 UML class diagram of the class BinaryTreeNode and the outer-inner class relationship
8
Java Programming: Program Design Including Data Structures8 Binary Trees (continued) Figure 19-8 Binary tree
9
Java Programming: Program Design Including Data Structures9 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 X 0, X 1,..., X n such that: X = X 0,X n = Y X i-1 is the parent of X i for all i = 1, 2,..., n
10
Java Programming: Program Design Including Data Structures10 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
11
Java Programming: Program Design Including Data Structures11 Binary Trees (continued) Method height private int height(BinaryTreeNode p) { if (p == null) return 0; else return 1 + Math.max(height(p.lLink), height(p.rLink)); }
12
Java Programming: Program Design Including Data Structures12 Copy Tree Method copyTree private BinaryTreeNode copyTree (BinaryTreeNode otherTreeRoot) { BinaryTreeNode temp; if (otherTreeRoot == null) temp = null; else { temp = (BinaryTreeNode ) otherTreeRoot.clone(); temp.lLink = copyTree(otherTreeRoot.lLink); temp.rLink = copyTree(otherTreeRoot.rLink); } return temp; }//end copyTree
13
Java Programming: Program Design Including Data Structures13 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
14
Java Programming: Program Design Including Data Structures14 Inorder Traversal Binary tree is traversed as follows: Traverse left subtree Visit node Traverse right subtree
15
Java Programming: Program Design Including Data Structures15 Inorder Traversal (continued) Method inOrder private void inorder(BinaryTreeNode p) { if (p != null) { inorder(p.lLink); System.out.print(p + “ “); inorder(p.rLink); }
16
Java Programming: Program Design Including Data Structures16 Preorder Traversal Binary tree is traversed as follows: Visit node Traverse left subtree Traverse right subtree
17
Java Programming: Program Design Including Data Structures17 Preorder Traversal (continued) Method preOrder private void preorder(BinaryTreeNode p) { if (p != null) { System.out.print(p + “ “); preorder(p.lLink); preorder(p.rLink); }
18
Java Programming: Program Design Including Data Structures18 Postorder Traversal Binary tree is traversed as follows: Traverse left subtree Traverse right subtree Visit node
19
Java Programming: Program Design Including Data Structures19 Postorder Traversal (continued) Method postOrder private void postorder(BinaryTreeNode p) { if (p != null) { postorder(p.lLink); postorder(p.rLink); System.out.print(p + “ “); }
20
Java Programming: Program Design Including Data Structures20 Implementing Binary Trees Figure 19-11 UML class diagram of the interface BinaryTreeADT
21
Java Programming: Program Design Including Data Structures21 Implementing Binary Trees (continued) Figure 19-12 UML class diagram of the class BinaryTree
22
Java Programming: Program Design Including Data Structures22 Implementing Binary Trees (continued) Method clone public Object clone() { BinaryTree copy = null; try { copy = (BinaryTree ) super.clone(); } catch (CloneNotSupportedException e) { return null; } if (root != null) copy.root = copyTree(root); return copy; }
23
Java Programming: Program Design Including Data Structures23 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
24
Java Programming: Program Design Including Data Structures24 Binary Search Trees (continued) Figure 19-14 Binary search tree
25
Java Programming: Program Design Including Data Structures25 Binary Search Trees (continued) Figure 19-15 UML class diagram of the class BinarySearchTree and the inheritance hierarchy
26
Java Programming: Program Design Including Data Structures26 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
27
Java Programming: Program Design Including Data Structures27 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
28
Java Programming: Program Design Including Data Structures28 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
29
Java Programming: Program Design Including Data Structures29 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
30
Java Programming: Program Design Including Data Structures30 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.39log 2 n = O(log 2 n) Average number of key comparisons 2.77log 2 n = O(log 2 n)
31
Java Programming: Program Design Including Data Structures31 Nonrecursive Binary Tree Traversal Algorithms Traversal algorithms Inorder Preorder Postorder
32
Java Programming: Program Design Including Data Structures32 Nonrecursive Inorder Traversal Method nonRecursiveInTraversal public void nonRecursiveInTraversal() { LinkedStackClass > stack = new LinkedStackClass >(); BinaryTreeNode current; current = root; while ((current != null) || (!stack.isEmptyStack())) if (current != null) { stack.push(current); current = current.lLink; }
33
Java Programming: Program Design Including Data Structures33 Nonrecursive Inorder Traversal (continued) else { current = (BinaryTreeNode ) stack.peek(); stack.pop(); System.out.print(current.info + “ “); current = current.rLink; } System.out.println(); }
34
Java Programming: Program Design Including Data Structures34 Nonrecursive Preorder Traversal General algorithm create 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 }
35
Java Programming: Program Design Including Data Structures35 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
36
Java Programming: Program Design Including Data Structures36 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
37
Java Programming: Program Design Including Data Structures37 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
38
Java Programming: Program Design Including Data Structures38 AVL (Height-Balanced) Trees(continued) Figure 19-24 Perfectly balanced binary tree
39
Java Programming: Program Design Including Data Structures39 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
40
Java Programming: Program Design Including Data Structures40 AVL (Height-Balanced) Trees (continued) Figure 19-25 Perfectly balanced binary tree
41
Java Programming: Program Design Including Data Structures41 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)
42
Java Programming: Program Design Including Data Structures42 Insertion into AVL Trees (continued) Figure 19-27 AVL tree before inserting 90
43
Java Programming: Program Design Including Data Structures43 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
44
Java Programming: Program Design Including Data Structures44 Insertion into AVL Trees (continued) Figure 19-29 AVL tree of Figure 19-27 after inserting 90 and adjusting the balance factors
45
Java Programming: Program Design Including Data Structures45 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
46
Java Programming: Program Design Including Data Structures46 AVL Tree Rotations (continued) Figure 19-39 Left rotation at a
47
Java Programming: Program Design Including Data Structures47 AVL Tree Rotations (continued) Figure 19-39 Right rotation at b
48
Java Programming: Program Design Including Data Structures48 AVL Tree Rotations (continued) Method rotateToLeft private AVLNode rotateToLeft(AVLNode root) { AVLNode 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
49
Java Programming: Program Design Including Data Structures49 AVL Tree Rotations (continued) Method rotateToRight private AVLNode rotateToRight(AVLNode root) { AVLNode 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
50
Java Programming: Program Design Including Data Structures50 AVL Tree Rotations (continued) Figure 19-44 AVL tree after inserting 40 Figure 19-45 AVL tree after inserting 30
51
Java Programming: Program Design Including Data Structures51 AVL Tree Rotations (continued) Figure 19-46 AVL tree after inserting 20
52
Java Programming: Program Design Including Data Structures52 AVL Tree Rotations (continued) Figure 19-46 AVL tree after inserting 25
53
Java Programming: Program Design Including Data Structures53 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
54
Java Programming: Program Design Including Data Structures54 Height of AVL tree with n nodes (worst case) 1.44log 2 n = O(log 2 n) 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
55
Java Programming: Program Design Including Data Structures55 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
56
Java Programming: Program Design Including Data Structures56 Chapter Summary Binary trees Every node has only two children Left subtree Right subtree Binary tree traversal Inorder Preorder Postorder
57
Java Programming: Program Design Including Data Structures57 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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.