package brs.visitor; import brs.*; /** * An object-oriented leaf counter. Uses anonymous inner classes to "help" count * the leaves of a BiTree host. *@author Dung X. Nguyen - Copyright 2000 - All rights reserved. */ public class LeafCounter implements IVisitor { public final static LeafCounter Singleton = new LeafCounter (); private LeafCounter () { } /** * Returns 0 - empty tree has no leaf. * @param host * @param notUsed not needed. * @return Integer (0). */ public Object emptyCase (BiTree host, Object notUsed) { return new Integer (0); } /** * Asks the subtrees to "help" count the leaves. * @param host * @param notUsed not needed. * @return the number of leaves in the host. */ public Object nonEmptyCase (BiTree host, Object notUsed) { // passes the right subtree to the left subtree and asks it to help count the leaves. return host.getLeftSubTree().execute ( new IVisitor () { public Object emptyCase (BiTree h, Object hSib) // asks the sibling subtree of h, hSib, to "help" count. { return ((BiTree)hSib).execute ( new IVisitor () { public Object emptyCase (BiTree st, Object inpNotUsed) // host is a leaf, and the leaf count is 1. { return new Integer (1); } public Object nonEmptyCase (BiTree st, Object inpNotUsed) // the leaf count is just the leaf count of hSib (i.e. st). { return st.execute (LeafCounter.Singleton, null); } } , null); } public Object nonEmptyCase (BiTree h, Object hSib) // host's leaf count is the sum of the subtrees' leaf count. { Integer hCount = (Integer)h.execute (LeafCounter.Singleton, null); Integer sibCount = (Integer)((BiTree)hSib).execute (LeafCounter.Singleton, null); return new Integer (hCount.intValue () + sibCount.intValue ()); } } , host.getRightSubTree ()); } /** * @param args == null - not used. */ public static void main(String[] args) { Integer level0 = new Integer (0); BiTree t0 = new BiTree (); System.out.println ("t0 is:\n " + t0); System.out.println("\nt0 leaf count is: " + t0.execute(LeafCounter.Singleton, null)); t0.insertRoot (new Integer (5)); BiTree t1 = new BiTree (); t1.insertRoot (new Integer (-7)); BiTree t2 = new BiTree (); t2.insertRoot (new Integer (3)); System.out.println ("\nt2 is:\n" + t2); System.out.println("\nt2 leaf count is: " + t2.execute(LeafCounter.Singleton, null)); t1.setLeftSubTree(t0); System.out.println ("\nt1 is:\n " + t1); System.out.println("\nt1 leaf count is: " + t1.execute(LeafCounter.Singleton, null)); t1.setRightSubTree (t2); System.out.println ("\nt1 is:\n " + t1); System.out.println("\nt1 leaf count is: " + t1.execute(LeafCounter.Singleton, null)); } }