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

Slides:



Advertisements
Similar presentations
Binary Trees CSC 220. Your Observations (so far data structures) Array –Unordered Add, delete, search –Ordered Linked List –??
Advertisements

Expression Trees What is an Expression tree? Expression tree implementation Why expression trees? Evaluating an expression tree (pseudo code) Prefix, Infix,
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 11 Implementing.
Main Index Contents 11 Main Index Contents Week 6 – Binary Trees.
Trees Chapter 8.
Fall 2007CS 2251 Trees Chapter 8. Fall 2007CS 2252 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information.
Main Index Contents 11 Main Index Contents Tree StructuresTree Structures (3 slides) Tree Structures Tree Node Level and Path Len. Tree Node Level and.
Trees Chapter 8. Chapter 8: Trees2 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information To learn how.
Trees Chapter 8. Chapter 8: Trees2 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information To learn how.
1 Introduction to Binary Trees. 2 Background All data structures examined so far are linear data structures. Each element in a linear data structure has.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 26 Binary Search Trees.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L12 (Chapter 20) Lists, Stacks,
Transforming Infix to Postfix
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 12 – Data Structures Outline 12.1Introduction.
Chapter 12 Trees. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Define trees as data structures Define the terms.
Binary and Other Trees CSE, POSTECH. 2 2 Linear Lists and Trees Linear lists are useful for serially ordered data – (e 1,e 2,e 3,…,e n ) – Days of week.
The Stack and Queue Types Lecture 10 Hartmut Kaiser
CS 146: Data Structures and Algorithms June 18 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
CS 46B: Introduction to Data Structures July 30 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 18 Binary.
Trees Chapter 8. 2 Tree Terminology A tree consists of a collection of elements or nodes, organized hierarchically. The node at the top of a tree is called.
Trees. Tree Terminology Chapter 8: Trees 2 A tree consists of a collection of elements or nodes, with each node linked to its successors The node at the.
Lecture Objectives  To learn how to use a tree to represent a hierarchical organization of information  To learn how to use recursion to process trees.
1 Stacks Chapter 4 2 Introduction Consider a program to model a switching yard –Has main line and siding –Cars may be shunted, removed at any time.
CSC 205 Programming II Postfix Expressions. Recap: Stack Stack features Orderly linear structure Access from one side only – top item Stack operations.
(c) University of Washington20d-1 CSC 143 Java Applications of Trees.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Lecture Objectives  To learn how to use a tree to represent a hierarchical organization of information  To learn how to use recursion to process trees.
Trees.ppt1 Introduction Many data structures are linear –unique first component –unique last component –other components have unique predecessor and successor.
Searching: Binary Trees and Hash Tables CHAPTER 12 6/4/15 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,
Trees. Containers we have studied so far are linear. To represent nonlinear, i.e. hierarchal data we use trees. Nonlinear Containers root node leaf edge.
Lecture 10 Trees –Definiton of trees –Uses of trees –Operations on a tree.
Binary Trees Chapter Definition And Application Of Binary Trees Binary tree: a nonlinear linked list in which each node may point to 0, 1, or two.
Topic 14 The BinaryTree ADT Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms.
Trees Chapter 8. Chapter 8: Trees2 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information To learn how.
Spring 2010CS 2251 Trees Chapter 6. Spring 2010CS 2252 Chapter Objectives Learn to use a tree to represent a hierarchical organization of information.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 20 Lists, Stacks,
Tree (new ADT) Terminology:  A tree is a collection of elements (nodes)  Each node may have 0 or more successors (called children)  How many does a.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 16 Binary.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 8 Collection.
Trees Chapter 8. 2 Tree Terminology A tree consists of a collection of elements or nodes, organized hierarchically. The node at the top of a tree is called.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 13 Implementing.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 14 Stacks.
IKI 10100I: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100I: Data.
1 Trees 2 Binary trees Section Binary Trees Definition: A binary tree is a rooted tree in which no vertex has more than two children –Left and.
Copyright © 2012 Pearson Education, Inc. Chapter 20: Binary Trees.
Tree Implementations Chapter 24 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures and Abstractions with Java,
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 20: Binary Trees.
BINARY TREES Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary.
Stacks Chapter 5 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures and Abstractions with Java, 4e Frank Carrano.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 20 Ordered.
Chapter 10 Trees © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 20: Binary Trees.
IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture13.
1 Trees. 2 Trees Trees. Binary Trees Tree Traversal.
Data Structures for Java William H. Ford William R. Topp
The Tree ADT.
Podcast Ch17b Title: Iterative Tree Traversal
Chapter 12 – Data Structures
Podcast Ch17d Title: Drawing a Binary Tree
Copyright ©2012 by Pearson Education, Inc. All rights reserved
Podcast Ch17a Title: Expression Trees
Stacks Chapter 4.
Chapter 20: Binary Trees.
Chapter 21: Binary Trees.
Stacks Chapter 5 Adapted from Pearson Education, Inc.
Data Structures for Java William H. Ford William R. Topp
Podcast Ch18b Title: STree Class
Stacks.
BINARY TREE CSC248 – Data Structure.
Presentation transcript:

© 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

© 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.

© 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

© 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

© 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.

© 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.

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

© 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++;

© 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();

© 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); }

© 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; }

© 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.

© 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");

© 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(""); }

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

© 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.

© 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.

© 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.

© 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.

© 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.

© 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.

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

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

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

© 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.

© 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) {...} }

© 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; }

© 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); }

© 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.

© 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; }

© 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.

© 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.

© 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");

© 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); }

© 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

© 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.

© 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.

© 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 / +

© 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

© 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.

© 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; }

© 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();

© 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))

© 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.

© 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.

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

© 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.

© 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.

© 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 () {} }

© 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.

© 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);

© 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; }

© 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);

© 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;

© 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);

© 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();

© 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);

© 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; }