dvanced Java Concepts Unit 5: Trees. Notes and Exercises Tree is a data structure like the figure shown below. We don t usually care about unordered trees but that s where we ll start. Later we will focus on ordered trees because they support efficient searching. Please read the following short discussion about where binary trees are used: http://stackoverflow.com/questions/210416/what-are-the-applications-of-binary-trees Vocabulary H Each node in a tree can have multiple successors and all items, except for the root, have exactly one predecessor. G Q node s predecessor is called its parent. node s successors are called its children. node that has no children is called a leaf. The line that connects a parent to its child is called an edge or branch. path is a sequence of edges that connect a node and one of its descendants. Path length refers to the number of edges in a path. The level of a node equals the length of the path connecting it to the root. Therefor the root is always at level zero. Note. pparently these definitions vary a little from source to source but these are the definitions that we will use. Questions. Use the above figure to answer the following questions. H The root is Name all the leaves in this tree: 2 Node is at level, N, The length of the path from Node to Node H is N E binary tree is a tree where each node has a maximum of two children, referred to as the left child and right child. We will only work with binary trees. binary tree is called a recursive structure because each subset is itself a binary tree, called the left or right subtree of the original tree. Page 1
Traversing a Tree. Traversal Method Definition ecursive Definition ample Tree B C Inorder left-root-right If root is not null: Traverse the left subtree inorder Visit the root Traverse the right subtree inorder Preorder root-left-right If root is not null: Visit the root Traverse the left subtree preorder Traverse the right subtree preorder Postorder left- right- root If root is not null: Traverse the left subtree postorder Traverse the right subtree postorder Visit the root Level root, level 1, order level 2, etc. Inorder traversal produces: BC Preorder traversal produces: BC Postorder traversal produces: BC Level order produces: BC Example. left subtree inorder root right subtree inorder Inorder traversal yields: W H X Y H X W Y root left subtree preorder right subtree preorder Preorder traversal yields: X H W Y left subtree postorder right subtree postorder Postorder traversal yields: W H Y X root root level 1 level 2 Level order traversal yields: X H W Y Page 2
Ex 1. What is the level of? What is the level of? What is the level of W? 0 1 1 2, F,,, W,, F, W, F,,, W,,, W, F, What is the length of the path from to? Inorder traversal yields Preorder traversal yields Postorder traversal yields Level order traversal yields F W Ex 2. What is the level of P? 1 W,, Z, E, P,,, W, E, Z, P W, Z, P, E,,,, W, E, Z, P What is the length of the path from to? Inorder traversal yields Preorder traversal yields Postorder traversal yields Level order traversal yields How many leaves are in this tree? W Z E P Ex. P B, F, G, H, P,,, T, W, Y, Z P, F, B, H, G,,, Y, T, W, Z B B, G, H, F,, W, T, Z, Y,, P P, F,, B, H,, Y, G, T, Z, W Inorder traversal yields Preorder traversal yields Postorder traversal yields Level order traversal yields F G H T Y Z Ex 4. W D, G, B,, H, E, I, C, F, B, D, G, C, E, H, I, F G, D, B, H, I, E, F, C,, B, C, D, E, F, G, H, I 4 Inorder traversal yields Preorder traversal yields Postorder traversal yields Level order traversal yields How many leaves are in this tree? D B G H E C I F Page
Practice-It! Do the traveral1, traversal2, and traversal problems under Binary Trees in CE 14. The remaining exercises in Binary Trees involve adding methods to the IntTree class. This class uses a nested class named IntTreeNode which has three instance variables (left, right, and data) that are accessible from within the IntTree class. Here is the solution for the size exercise: public int size(){ return size( overalloot ); private int size( IntTreeNode root ){ if ( root == null ) return 0; else return 1 + size( root.left ) + size( root.right ); Use the above solution as a model and solve the following problems. countleaves sum countleftnodes depthum doublepositives numempty height isfull printlevel writetree Binary Expression Tree binary expression tree consists of either a single root (containing an operand) or stores a mathematical expression according to this rule: The root contains an operator that will be applied to the results of evaluating the expressions in the left and right subtrees, each of which is a binary expression tree. Each of these trees is a binary expression tree. 4 1. What does a preorder traversal yield? 2. What does a postorder traversal yield?. What does an inorder traversal yield? 4. What is the value of this expression? (use any of the above expressions) 5. What does a preorder traversal yield? 6. What does a postorder traversal yield? 7. What does an inorder traversal yield?. What is the value of this expression? * 9 + 2 9 2 + * 9 * ( 2 + ) 45 9 * + 2 Page 4
9. What does a preorder traversal yield? 10. What does a postorder traversal yield? 11. What does an inorder traversal yield?. What is the value of this expression? * - + 4 2-4 2 + * ( - ) * ( 4 + 2 ) 0 * - + 4 2 Notice. preorder traversal yields the prefix form. postorder traversal yields the postfix form. n inorder traversal yields the infix form except that you might have to add parentheses. The level of the nodes indicates the precedence. The operation at the root will always be the last operation performed. Operations in the highest level nodes (which is the bottom) are performed first. The evaluation of a binary expression tree is a recursive process because each subtree is itself another binary expression tree. Binary earch Tree. In a binary search tree, the left child is always less than its parent. The right child is always greater than the parent. There should be no duplicates. ctually, depending on whose definition you use there may be duplicates. In this course there are never any duplicates. Here is an example of a binary search trees. 0 7-1 5 9 Because of the recursive nature of a tree, everything in the left subtree of a binary search tree is less than the root. nd everything in the right tree is greater than the root. For a binary search tree, an inorder traversal gets the nodes in ascending order from least to greatest. Page 5
dding a value to a BT is rather simple. Compare the new value to the root value. If the root is null, then the value becomes the root node. If the new value is less than the root value, then compare it to the left node and repeat the process. If the new value is greater than the root value, then compare it to the right node and repeat the process. ample Problem 1. Create a BT by adding these numbers, in order:,, 5, 9 tep 1. The first number becomes the root. tep 2. ince the is less than, it becomes the left node. tep. ince the 5 is less than, we move its left node. ince 5 is greater than the, the new node becomes the right child of the node. 5 9 tep 4. ince the 9 is greater the, it goes to the right. ample Problem 2. 5 The BT to the right results from adding the following numbers in order 5, 0, 9, 7,, -1, 0 5 9 Note that a different shape tree will result if the order of the numbers is changed. -1 7 Ex 5. Which of these trees are valid binary search trees? C Tree T T W Tree B Tree C W W T Page 6
Ex 6. Draw a binary search tree that consists of these numbers: 2, 6,, 14 (added in this order). 2 6 14 Ex 7. Draw a binary search tree that consists of these numbers: 6, 2,, -2, 5, 7, 14 (added in this order). 6 2-2 5 7 14 Ex. Draw a binary search tree that consists of these numbers: H, B,, N, C,, J (added in this order). B C H J N Ex 9. Draw a binary search tree that consists of the letters in: MNICUE (added in this order). C E I M N U Ex 10. Below is a binary search tree. If 15 is added to the tree, show where it would be placed. 2 2 45 1 22 2 17 Ex 11. < x < Ex. < x < 15 5 9 1 x 5 x 0 60 5 9 2 7 Page 7
To delete a node from a tree is a little more complicated. There are three cases to consider. In all cases you must first find the item to remove ND keep a reference to its parent. Case 1. The item to be removed has no children. olution. et the appropriate pointer in the parent (left or right child) to null. Case 2. The item to be removed has 1 child. olution. et the appropriate reference in the parent (of the node to be deleted) to the child. Example. uppose we want to remove the 21. 15 4 21 15 4 17 17 1 1 Case. The item to be removed has 2 children. (This is the tricky one.) olution. One approach is to (1) search for the smallest item in the item's right subtree. (2) replace the data to be removed with the data from the smallest item. () remove the smallest item from the right subtree (which will be easy because it will have (at most) one child. Example. uppose we want to remove the 7. 7 11 4 4 11 4 11 4 tep 1. Find the smallest value in the right subtree (11) 11 4 tep 2. eplace the 7 with the 11. 4 tep. emove the original 11. Ex 1. edraw this tree after the is deleted. 20 7 50 20 7 50 65 65 Page
Ex 14. edraw this tree after the 65 is deleted. 20 20 7 50 7 50 65 Ex 15. edraw this tree after the 20 is deleted. 20 7 50 7 50 65 65 Ex 16. edraw this tree after the 0 is deleted. 44 44 25 70 25 70 57 0 57 75 94 75 94 9 9 Page 9
Ex 17. edraw this tree after the 70 is deleted and then 44 is deleted. 44 25 70 57 75 0 94 9 57 25 75 0 94 9 Ex 1. Draw a binary search where the numbers have been added in this order:, 14, 44, 24 Then the 14 is deleted and then 14 is added to the tree again. 14 24 44 Ex 19. Draw a binary search where the numbers have been added in this order: 60, 50, 40, 0, 45 Then 60 is deleted, 56 is added, and 40 is deleted. 0 50 45 56 Ex 20. Draw a binary search where the numbers have been added in this order: 5, 70, 51, 66, 75, 1, 77 Then 70 is deleted and 5 is deleted. 66 51 75 77 1 Ex 21. dd these numbers in this order: 70, 2, 45, 5, 2, 7. Then remove the 70 and add 61. 7, 2, 45, 5, 61, 2 61, 5, 45, 2, 2, 7 2, 45, 5, 61, 7, 2 What does a preorder traversal yield? What does a postorder traversal yield? What does an inorder traversal yield? Ex 22. dd these numbers in this order: 5,, 9, 1, 7, 4, 6. Then remove the 9 and add. 5,, 1, 7, 6, 1,, 6,, 7, 5 1,, 5, 6, 7, What does a preorder traversal yield? What does a postorder traversal yield? What does an inorder traversal yield? Page 10
Implementation of a Binary earch Tree. Here s the first version our BT of trings. public class BT{ private Node root; public BT(){ root = null; public void add( tring str ){ Node node = new Node( str ); if ( root == null ) root = node; else add( root, node ); private void add( Node n, Node newnode ){ // precondition: n is not null int comparevalue = newnode.compareto( n ); if ( comparevalue == 0 ) // already in the tree return; // no duplicates allowed else if ( comparevalue < 0 && n.left == null ) n.left = newnode; else if ( comparevalue < 0 ) add( n.left, newnode ); else if ( comparevalue > 0 && n.right == null ) n.right = newnode; else add( n.right, newnode ); private class Node implements Comparable<Node> { private tring s; private Node left, right; private Node( tring s ){ if ( s == null ) throw new IllegalrgumentException( "What?!" ); this.s = s; left = null; right = null; public int compareto( Node n ){ return s.compareto( n.s ); public boolean equals( Node n ){ if ( n == null ) return false; return this.s.equals( n.s ); Page 11
Program Modification 1. dd and complete the following methods for the BT class. public void postorder(){ if ( root == null ) return; else postorder( root ); ystem.out.println(); private void postorder(node n ){ Complete this method. It should traverse and print out the contents of the tree in post-order. This can be done with 5 lines of code. Test this using the code below public class unbt{ public static void main( tring [] args ){ BT b1 = new BT(); b1.add( "M" ); b1.add( "Z" ); b1.add( "" ); b1.add( "C" ); b1.postorder(); // C Z M BT b2 = new BT(); b2.add( "Z" ); b2.add( "C" ); b2.add( "M" ); b2.add( "" ); b2.postorder(); // M C Z Program Modification 2. dd and complete the following methods for the BT class. public tring findmallest(){ This returns the least string in the tree (but does not delete it). You should write a private recursive helper method. If the root is null then return null. Test this using the code below BT b1 = new BT(); b1.add( "K" ); b1.add( "E" ); b1.add( "W" ); b1.add( "F" ); ystem.out.println( b1.findmallest() ); // E Page
Program Modification. Here s the big one. Write the remove method. public void remove( tring str ){ Delete the string from the tree following the guidelines discussed earlier. If the string is not in the tree then do nothing. This is not a simple method. t some point you will make a recursive call to a method. When you do, you will need to pass the string, the node you are checking, and the parent of the node you are checking. You may want to write a search method that searches the tree for str. Then if it finds it, then call a private helper method to delete that node. Use the following code to test your program. fter adding all the letters BT b1 = new BT(); b1.add( "M" ); b1.add( "G" ); b1.add( "" ); b1.add( "K" ); b1.add( "" ); b1.add( "" ); b1.add( "Z" ); b1.postorder(); // K G Z M G K M Z b1.remove("k"); b1.postorder(); // G Z M b1.remove("g"); b1.postorder(); b1.remove("m"); b1.postorder(); // Z M // Z Z b1.add( "P" ); b1.add( "X" ); b1.postorder(); // P X Z lso test your code with this: BT b2 = new BT(); b2.add( "" ); b2.add( "K" ); b2.add( "" ); b2.postorder(); // K b2.remove( "" ); b2.postorder(); // K P X Z Page 1