Date: Wed, 2 Feb 2005 17:48:13 +0000 (UTC)
From: John B. Clements <clements@ccs.neu.edu>
Newsgroups: ccs.courses.csu213
Subject: code from class, 2005-01-31

Code from class, as promised:

/*
           +---------+               
           | BinTree |<-------------+
           +---------+              |
           +---------+              |
               / \                  |
               ---                  |
                |                   |
      ------------------            |
      |                |            |
  +-------+    +---------------+    |
  | Leaf  |    | Branch        |    |
  +-------+    +---------------+    |
  | int n |    | BinTree left  |-+  |
  +-------+    | BinTree right |-+  |
               +---------------+ |  |
                                 |  |
                                 +--+

*/

// represent Binary Trees
abstract class BinTree {

// represent Binary Trees
abstract class BinTree {
  abstract int addLeaves();
  abstract boolean same(BinTree bt);
  abstract boolean sameBranch(Branch br);
  abstract boolean sameLeaf(Leaf l);
  abstract int longestPath();
}

// represent a Leaf
class Leaf extends BinTree {
  int n;

  Leaf(int n) {
    this.n = n;
  }
  int addLeaves(){
    return this.n;
  }

  boolean same(BinTree bt){
    return bt.sameLeaf(this);
  }

  boolean sameBranch(Branch br){
    return false;  
  }

  boolean sameLeaf(Leaf l){
    return this.n == l.n;


  boolean sameLeaf(Leaf l){
    return this.n == l.n;
  }

  int longestPath(){
    return 0;
  }
}

// represents a Branch
class Branch extends BinTree {
  BinTree left;
  BinTree right;

  Branch(BinTree left, BinTree right) {
    this.left = left;
    this.right = right;
  }

  int addLeaves(){
    return (this.left.addLeaves() + this.right.addLeaves());
  }

  boolean same(BinTree bt){
    return bt.sameBranch(this);
  }

  boolean sameBranch(Branch br){
    return this.left.same(br.left) && this.right.same(br.right);
  }


    return this.left.same(br.left) && this.right.same(br.right);
  }

  boolean sameLeaf(Leaf l){
    return false;
  }

  int longestPath(){
   if (this.left.longestPath() > this.right.longestPath())
    return 1+ this.left.longestPath();
   else
    return 1+ this.right.longestPath();
  }
}

class Examples{
  Examples(){}

  BinTree bt = new Branch(new Leaf(5),
                          new Branch(new Branch(new Leaf(9),new Leaf(5)),
                                     new Leaf(7)));

  boolean t0 = (this.bt.same(this.bt) == true);

  boolean t1 = (this.bt.addLeaves() == 26);

  int t2 = (this.bt.longestPath());
}


