// Source code example for "A Practical Introduction // to Data Structures and Algorithm Analysis" // by Clifford A. Shaffer, Prentice Hall, 1998. // Copyright 1998 by Clifford A. Shaffer import java.io.*; // Leaf and internal node classes for variable node // implementation of BinNode. // The implementation is for an expression tree. // The internal nodes store a single character for an // operator, and two child pointers. // The leaf nodes store a string for an operand. class LeafNode implements BinNode { // Leaf node subclass private String var; // Operand value public LeafNode(String val) { var = val; } // Constructor public Object element() { return var; } public Object setElement(Object v) { return var = (String)v; } public BinNode left() { return null; } public BinNode setLeft(BinNode p) { return null; } public BinNode right() { return null; } public BinNode setRight(BinNode p) { return null; } public boolean isLeaf() { return true; } } // class LeafNode class IntlNode implements BinNode { // Internal node subclass private BinNode left; // Left child private BinNode right; // Right child private Character opx; // Operator value public IntlNode(Character op, BinNode l, BinNode r) { opx = op; left = l; right = r; } // Constructor public Object element() { return opx; } public Object setElement(Object v) { return opx = (Character)v; } public BinNode left() { return left; } public BinNode setLeft(BinNode p) { return left = p; } public BinNode right() { return right; } public BinNode setRight(BinNode p) { return right = p; } public boolean isLeaf() { return false; } } // class IntlNode // Driver class for variable BinNode implementation class VarMain { static void VisitLeafNode(Object val) { System.out.println("Leaf: " + val); } static void VisitInternalNode(Object val) { System.out.println("Internal: " + val); } // Traverse a binary tree implemented with variable // BinNode implementation static void traverse(BinNode rt) { // Preorder traversal if (rt == null) return; // Nothing to visit if (rt.isLeaf()) // Process leaf node VisitLeafNode(rt.element()); else { // Processinternal node VisitInternalNode(rt.element()); traverse(rt.left()); traverse(rt.right()); } } // Main routine for variable BinNode test public static void main(String args[]) throws IOException { BinNode temp1, temp2, root; String string1 = "Hello1"; String string2 = "Another string"; temp1 = new LeafNode(string1); temp2 = new LeafNode(string2); root = new IntlNode(new Character('+'), temp1, temp2); traverse(root); System.in.read(); } }