Presentation is loading. Please wait.

Presentation is loading. Please wait.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 17 Binary.

Similar presentations


Presentation on theme: "© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 17 Binary."— Presentation transcript:

1 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 17 Binary Tree Applications Bret Ford © 2005, Prentice Hall

2 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Expression Trees A binary expression tree represents an arithmetic expression. A binary expression tree represents an arithmetic expression. In an expression tree each operator is an interior node whose children are operands or subexpressions. Operands are in leaf nodes. In an expression tree each operator is an interior node whose children are operands or subexpressions. Operands are in leaf nodes.

3 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Expression Trees (continued) The preorder and postorder traversals of a binary expression tree produce the prefix and postfix (RPN) notation for the expression. The preorder and postorder traversals of a binary expression tree produce the prefix and postfix (RPN) notation for the expression. An inorder traversal generates the infix form of the expression, assuming that parentheses are not needed to determine the order of evaluation An inorder traversal generates the infix form of the expression, assuming that parentheses are not needed to determine the order of evaluation

4 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Expression Trees (continued) Preorder(Prefix):- + a / * b c d e// preorder scan Inorder(Infix):a + b * c / d - e// inorder scan Postorder(Postfix):a b c * d / + e -// postorder scan

5 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Building a Binary Expression Tree Build an expression tree from a postfix expression using an iterative algorithm. An operand is a single character such as 'a' or 'b'. Build an expression tree from a postfix expression using an iterative algorithm. An operand is a single character such as 'a' or 'b'. If the token is an operand, create a leaf node whose value is the operand and whose left and right subtrees are null. Push the node onto a stack of TNode references. If the token is an operand, create a leaf node whose value is the operand and whose left and right subtrees are null. Push the node onto a stack of TNode references.

6 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Building a Binary Expression Tree (continued) If the token is an operator, create a new node with the operator as its value. Pop the two child nodes from the stack and attach them to the new node. The first child popped from the stack becomes the right subtree of the new node and the second child popped from the stack becomes the left subtree. If the token is an operator, create a new node with the operator as its value. Pop the two child nodes from the stack and attach them to the new node. The first child popped from the stack becomes the right subtree of the new node and the second child popped from the stack becomes the left subtree.

7 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Building a Binary Expression Tree (continued) a b c * +

8 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.buildExpTree() public static TNode buildExpTree( String postfixExp) { // newNode is a reference to the root of subtrees // we build, and newLeft/newRight are its children TNode newNode, newLeft, newRight; char token; // subtrees go into and off the stack ALStack > s = new ALStack< TNode >(); int i = 0, n = postfixExp.length(); // loop until i reaches the end of the string while(i != n) { // skip blanks and tabs in the expression while (postfixExp.charAt(i) == ' ' || postfixExp.charAt(i) == '\t') i++;

9 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. buildExpTree() (continued) // if the expression has trailing whitespace, // we could be at the end of the string if (i == n) break; // extract the current token and increment i token = postfixExp.charAt(i); i++; // see if the token is an operator or an operand if (token == '+' || token == '-' || token == '*' || token == '/') { // current token is an operator; pop two // subtrees off the stack newRight = s.pop(); newLeft = s.pop();

10 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. buildExpTree() (continued) // create a new subtree with token as root and // subtrees newLeft and newRight and push it // onto the stack newNode = new TNode (token, newLeft,newRight); s.push(newNode); } else // must be an operand { // create a leaf node and push it onto the stack newNode = new TNode (token); s.push(newNode); }

11 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. buildExpTree() (concluded) // if the expression was not empty, the root of // the expression tree is on the top of the stack if (!s.isEmpty()) return s.pop(); else return null; }

12 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 17.1 In a GUI application, a user enters a correctly formed postfix expression in a text field and presses the Enter key. An event handler displays the expression in a text area and then calls buildExpTree() to construct the corresponding binary expression tree. A call to displayTree() places the tree in the text area. The output concludes by displaying the preorder, inorder, and postorder scans of the tree. In a GUI application, a user enters a correctly formed postfix expression in a text field and presses the Enter key. An event handler displays the expression in a text area and then calls buildExpTree() to construct the corresponding binary expression tree. A call to displayTree() places the tree in the text area. The output concludes by displaying the preorder, inorder, and postorder scans of the tree.

13 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 17.1 (continued) public void actionPerformed(ActionEvent ae) { // obtain the expression the user typed String expression = expInput.getText(); // build the expression tree TNode root = BinaryTree.buildExpTree(expression); // output the expression and its tree textArea.append("Expression tree for " + expression + "\n\n"); textArea.append(BinaryTree.displayTree(root, 1) + "\n");

14 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 17.1 (concluded) // output the scans textArea.append("Preorder scan: " + BinaryTree.preorderDisplay(root) + "\n\n"); textArea.append("Inorder scan: " + BinaryTree.inorderDisplay(root) + "\n\n"); textArea.append("Postorder scan: " + BinaryTree.postorderDisplay(root) + "\n\n"); // clear the text field expInput.setText(""); }

15 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Run of Program 17.1

16 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Iterative Tree Traversal Traversing the nodes in a binary tree is more difficult than traversing a LinkedList or ArrayList collection since a tree is a nonlinear structure and there is no one traversal order (e.g. preorder, inorder, postorder). Traversing the nodes in a binary tree is more difficult than traversing a LinkedList or ArrayList collection since a tree is a nonlinear structure and there is no one traversal order (e.g. preorder, inorder, postorder). The problem with the recursive algorithms is that there is no escape from the recursive process until it completes. We need to simulate a recursive traversal with an iterative algorithm. The problem with the recursive algorithms is that there is no escape from the recursive process until it completes. We need to simulate a recursive traversal with an iterative algorithm.

17 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Iterative Tree Traversal (continued) Our binary tree iterator implements the Iterator interface by using a stack to hold the nodes which have been visited. Our binary tree iterator implements the Iterator interface by using a stack to hold the nodes which have been visited. The scan can halt at any time, the programmer can deal with a node, and then continue the scan. The scan can halt at any time, the programmer can deal with a node, and then continue the scan.

18 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Iterative Tree Traversal (continued) The figure gives a UML diagram for the class InorderIterator that includes the instance variables and the private method goFarLeft() which is critical to finding the "next" node. The figure gives a UML diagram for the class InorderIterator that includes the instance variables and the private method goFarLeft() which is critical to finding the "next" node.

19 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Iterative Tree Traversal (continued) Inorder Iterator Algorithm Inorder Iterator Algorithm Find the leftmost node in the tree by starting at the root and following the chain of left children until locating a node with an empty left subtree. During this process, the root and all intermediate nodes on the chain of left children are pushed on the stack. Find the leftmost node in the tree by starting at the root and following the chain of left children until locating a node with an empty left subtree. During this process, the root and all intermediate nodes on the chain of left children are pushed on the stack.

20 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Iterative Tree Traversal (continued) Inorder Iterator Algorithm (continued) Inorder Iterator Algorithm (continued) 1. Capture the value in the node. 2. If the right branch of the node is not empty, move to the right child and then traverse the chain of left children until locating a node with a null left subtree. This is the next node. During the traversal, push on the stack a reference to each node on the path.

21 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Iterative Tree Traversal (continued) Inorder Iterator Algorithm (concluded) Inorder Iterator Algorithm (concluded) 3. If the right branch of the node is empty, the scan of the node's left branch is complete, and the node itself has been visited. The next node to visit is on the stack. If the stack is not empty, pop it to determine the next node in the scan. If the stack is empty, all nodes have been visited and the scan concludes.

22 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Iterative Tree Traversal (continued)

23 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Iterative Tree Traversal (continued)

24 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Iterative Tree Traversal (continued)

25 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing the InorderIterator Class The InorderIterator class provides instances that execute an iterative inorder scan of a binary tree. The InorderIterator class provides instances that execute an iterative inorder scan of a binary tree. An InorderIterator object scans a binary tree and access the value of the elements. The remove() method throws an UnsupportedOperationException. An InorderIterator object scans a binary tree and access the value of the elements. The remove() method throws an UnsupportedOperationException. The instance variables include a stack for TNode references and the variable curr which references the next node. The end of a traversal occurs when curr becomes null. The instance variables include a stack for TNode references and the variable curr which references the next node. The end of a traversal occurs when curr becomes null.

26 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing the InorderIterator Class (continued) The class uses the private method goFarLeft() to locate the first element and to execute rule 2. The method begins at node t and stacks all of the nodes until it locates one with a null left subtree. A reference to this node is the return value. The class uses the private method goFarLeft() to locate the first element and to execute rule 2. The method begins at node t and stacks all of the nodes until it locates one with a null left subtree. A reference to this node is the return value. public class InorderIterator implements Iterator { private ALStack > s = null; private TNode curr = null;... private TNode goFarLeft(TNode t) {...} }

27 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing the InorderIterator Class (continued) // go far left from t, pushing all the nodes with // left children on stack s private TNode goFarLeft(TNode t) { if (t == null) return null; while (t.left != null) { s.push(t); t = t.left; } return t; }

28 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing the InorderIterator Class (continued) The constructor allocates the stack and calls goFarLeft() to position curr at the first node inorder. Since InorderIterator is not included in a collection class, a user must pass the root of the binary tree as an argument. The constructor allocates the stack and calls goFarLeft() to position curr at the first node inorder. Since InorderIterator is not included in a collection class, a user must pass the root of the binary tree as an argument. public InorderIterator(TNode root) { s = new ALStack >(); curr = goFarLeft(root); }

29 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing the InorderIterator Class (continued) The method next() implements Steps 1 through 3. In keeping with the requirements of the Iterator interface, next() throws NoSuchElementException if the tree traversal is complete. The method next() implements Steps 1 through 3. In keeping with the requirements of the Iterator interface, next() throws NoSuchElementException if the tree traversal is complete.

30 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing the InorderIterator Class (concluded) public T next() { if (curr == null) throw new NoSuchElementException( "InorderScan: no elements remaining"); // capture the value in the node T returnValue = curr.nodeValue; if (curr.right != null) // have a right subtree // stack nodes on left subtree curr = goFarLeft(curr.right); else if (!s.isEmpty()) // no right subtree; there are other nodes // to visit; pop the stack curr = (TNode )s.pop(); else // end of tree; set curr to null curr = null; return returnValue; }

31 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 17.2 The static method, buildTime24Tree() in the BinaryTree class builds the following binary tree of Time24 objects. The static method, buildTime24Tree() in the BinaryTree class builds the following binary tree of Time24 objects.

32 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 17.2 (continued) The program calls buildTime24Tree() to create the tree and then uses an inorder tree iterator to traverses the nodes. After each call to next(), the program updates the time value of the node by adding 60 minutes ( 1 hour). A call to displayTree() outputs the updated tree. The program calls buildTime24Tree() to create the tree and then uses an inorder tree iterator to traverses the nodes. After each call to next(), the program updates the time value of the node by adding 60 minutes ( 1 hour). A call to displayTree() outputs the updated tree.

33 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 17.2 (continued) import ds.util.TNode; import ds.util.BinaryTree; import ds.util.InorderIterator; import ds.time.Time24; public class Program17_2 { public static void main(String[] args) { // roots for the tree TNode root; // build a tree of Time24 data root = BinaryTree.buildTime24Tree(); // display the tree System.out.println("Original tree"); System.out.println(BinaryTree.displayTree( root, 5) + "\n");

34 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 17.2 (concluded) // declare an inorder tree iterator InorderIterator iter = new InorderIterator (root); // go through the tree and add 1 hour to each time while (iter.hasNext()) { // obtain the value in a tree node Time24 t = iter.next(); // add 1 hour to the time t.addTime(60); } System.out.println("Modified tree"); System.out.println(BinaryTree.displayTree(root, 5)); // delete the nodes in the tree BinaryTree.clearTree(root); }

35 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 17.2 (Run) Original tree 3:15 18:35 20:55 10:45 12:00 15:30 5:15 7:30 9:15 Modified tree 4:15 19:35 21:55 11:45 13:00 16:30 6:15 8:30 10:15

36 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Euler Tree Traversal Up to this point, all of our tree traversal algorithms visit each node exactly once. For instance, the inorder traversal visits the node between visiting the left subtree and the right subtree. Up to this point, all of our tree traversal algorithms visit each node exactly once. For instance, the inorder traversal visits the node between visiting the left subtree and the right subtree. We need a more general tree traversal algorithm for some applications, one that will visit each node more than once. The Euler tour traversal provides a solution. We need a more general tree traversal algorithm for some applications, one that will visit each node more than once. The Euler tour traversal provides a solution.

37 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Euler Tree Traversal (continued) The Euler tour is a walk around T, encountering each node three times: The Euler tour is a walk around T, encountering each node three times: On the left, before the Euler tour of the node's left subtree. On the left, before the Euler tour of the node's left subtree. From below, as we finish the tour of the left subtree. From below, as we finish the tour of the left subtree. On the right, after we finish the Euler tour of the right subtree. On the right, after we finish the Euler tour of the right subtree. If the node is a leaf, we consider the visits to all occur at once. If the node is a leaf, we consider the visits to all occur at once.

38 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Euler Tree Traversal (continued) The walk in the figure traverses an expression tree. The directed edges trace the Euler tour beginning with the root. The walk in the figure traverses an expression tree. The directed edges trace the Euler tour beginning with the root. Tour visits: + * a * - d - e - * + / b / c / +

39 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Euler Tree Traversal (continued) Algorithm eulerTour(TNode t): if t ≠ null if t is a leaf node visit t else visit t // on the left eulerTour(t.left); visit t;// from below eulerTour(t.right); visit t;// on the right

40 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Euler Tree Traversal (continued) Use an Euler tour to generate a fully parenthesized expression from an expression tree. Use an Euler tour to generate a fully parenthesized expression from an expression tree. A visit to an operand inserts the operand in the string. A visit to an operand inserts the operand in the string. For an operator, output a "(" for the visit on the left, output the operator for the visit from below, and output a ")" for the visit on the right. For an operator, output a "(" for the visit on the left, output the operator for the visit from below, and output a ")" for the visit on the right.

41 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Euler Tree Traversal (concluded) // traverse an expression tree and display the // equivalent fully parenthesized expression public static String fullParen(TNode t) { String s = ""; if (t != null) { if (t.left == null && t.right == null) s += t.nodeValue; // visit a leaf node else { s += "("; // visit on left s += fullParen(t.left); s += t.nodeValue; // visit from below s += fullParen(t.right); s += ")"; // visit on right } return s; }

42 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 17.3 import java.util.Scanner; import ds.util.TNode; import ds.util.BinaryTree; public class Program17_3 { public static void main(String[] args) { // prompt for the RPN expression Scanner keyIn = new Scanner(System.in); String postfixExp; // root of the expression tree TNode root; System.out.print("Enter a postfix expresssion: "); postfixExp = keyIn.nextLine();

43 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Program 17.3 (concluded) // build the expression tree root = BinaryTree.buildExpTree(postfixExp); // display the tree System.out.println("Expression tree"); System.out.println(BinaryTree.displayTree(root,1)); // output the full parenthesized expression System.out.print("Fully parenthesized expression: "); System.out.println(BinaryTree.fullParen(root)); } Enter a postfix expresssion: a d e - * b c / + Expression tree + * / a - b c d e Fully parenthesized expression: ((a*(d-e))+(b/c))

44 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Drawing a Binary Tree The methods displayTree(), drawTree(), and drawTrees() display a binary tree as a string or graphically. The algorithms employ many of the basic features of a binary tree. The methods displayTree(), drawTree(), and drawTrees() display a binary tree as a string or graphically. The algorithms employ many of the basic features of a binary tree.

45 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Drawing a Binary Tree (continued) View the display of the tree as a rectangular grid with a cell denoted by the pair (level, column). The level is a row in the grid corresponding to a level in the tree. The column coordinate designates a region of the display measured left to right. View the display of the tree as a rectangular grid with a cell denoted by the pair (level, column). The level is a row in the grid corresponding to a level in the tree. The column coordinate designates a region of the display measured left to right.

46 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Drawing a Binary Tree (continued)

47 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Drawing a Binary Tree (continued) The algorithm to display a tree is a two step process. The algorithm to display a tree is a two step process. 1. The first step uses the recursive function buildShadowTree() to carry out an inorder scan of the tree which creates a second tree, called a shadow tree. Its nodes store the value of the node in the original tree formatted as a string and the (level, col) position of the shadow tree node in the grid. 2. The second step performs a level order scan of the shadow tree to display the nodes.

48 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Building a Shadow Tree As buildShadowTree() uses an inorder scan it moves from one grid column to another. For instance, with Tree 0, the order of visit is B D A E C. Note in the figure that this is the column-order for the nodes in the tree. As buildShadowTree() uses an inorder scan it moves from one grid column to another. For instance, with Tree 0, the order of visit is B D A E C. Note in the figure that this is the column-order for the nodes in the tree.

49 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Building a Shadow Tree (continued) The nodes of a shadow tree are objects of type TNodeShadow. The nodes of a shadow tree are objects of type TNodeShadow. class TNodeShadow { public static int columnValue; public String nodeValueStr; // formatted node value public int level, column; public TNodeShadow left, right; public TNodeShadow () {} }

50 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Building a Shadow Tree (continued) Each recursive call of buildShadowTree() allocates a TNodeShadow object and assigns it the node value string. It then makes recursive calls that create the left and right subtrees. Each recursive call of buildShadowTree() allocates a TNodeShadow object and assigns it the node value string. It then makes recursive calls that create the left and right subtrees. Each recursive call in the inorder scan creates a node in the column specified by the static value columnValue and then increments the variable for the next recursive call. Each recursive call in the inorder scan creates a node in the column specified by the static value columnValue and then increments the variable for the next recursive call.

51 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.buildShadowTree() // recursive inorder scan used to build the shadow tree private static TNodeShadow buildShadowTree( TNode t, int level) { // reference to new shadow tree node TNodeShadow newNode = null; if (t != null) { // create the new shadow tree node newNode = new TNodeShadow(); // allocate node for left child at next level // in tree; attach node newNode.left = buildShadowTree(t.left, level+1);

52 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. buildShadowTree() (concluded) // initialize variables of the new node // format conversion newNode.nodeValueStr = t.nodeValue.toString(); newNode.level = level; newNode.column = TNodeShadow.columnValue; // update column to next cell in the table TNodeShadow.columnValue++; // allocate node for right child at next level // in tree; attach node newNode.right = buildShadowTree(t.right, level+1); } return newNode; }

53 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Displaying a Shadow Tree The method displayTree() takes the root, t, of the binary tree as an argument and calls buildShadowTree() to create the shadow tree. The method displayTree() takes the root, t, of the binary tree as an argument and calls buildShadowTree() to create the shadow tree. // build the shadow tree TNodeShadow shadowRoot = buildShadowTree(t, 0);

54 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Displaying a Shadow Tree (continued) Display the tree with a level order scan of the shadow tree. The scan uses the node data to position and display each node. Display the tree with a level order scan of the shadow tree. The scan uses the node data to position and display each node. // use for the level-order scan of the shadow tree LinkedQueue q = new LinkedQueue (); String displayStr = ""; int colWidth = maxCharacters + 1; int currLevel = 0, currCol = 0; // use during the level order scan of the shadow tree TNodeShadow currNode;

55 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.displayTree() // return a string that displays a binary tree; // output of a node value requires no more than // maxCharacters public static String displayTree(TNode t, int maxCharacters) { // use for the level-order scan of the shadow tree LinkedQueue q = new LinkedQueue (); String displayStr = ""; int colWidth = maxCharacters + 1; int currLevel = 0, currCol = 0; TNodeShadow.columnValue = 0; if (t == null) return displayStr; // build the shadow tree TNodeShadow shadowRoot = buildShadowTree(t, 0);

56 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. displayTree() (continued) // use during the level order scan of the shadow tree TNodeShadow currNode; // insert the root in the queue and set current // level to 0 q.push(shadowRoot); // continue the iterative process until the queue // is empty while(!q.isEmpty()) { // delete front node from queue and make it // the current node currNode = q.pop();

57 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. displayTree() (continued) // if level changes, output a newline if (currNode.level > currLevel) { currLevel = currNode.level; currCol = 0; displayStr += '\n'; } // if a left child exists, insert the child // in the queue if (currNode.left != null) q.push(currNode.left); // if a right child exists, insert the child // in the queue if (currNode.right != null) q.push(currNode.right);

58 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. displayTree() (concluded) // output formatted node value if (currNode.column > currCol) { displayStr += formatChar(( currNode.column - currCol) * colWidth, ' '); currCol = currNode.column; } displayStr += formatString(colWidth, currNode.nodeValueStr); currCol++; } displayStr += '\n'; // delete the shadow tree shadowRoot = clearShadowTree(shadowRoot); return displayStr; }


Download ppt "© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 17 Binary."

Similar presentations


Ads by Google