11.07.2015 Views

Data Structures and Algorithm Analysis - Computer Science at ...

Data Structures and Algorithm Analysis - Computer Science at ...

Data Structures and Algorithm Analysis - Computer Science at ...

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Sec. 5.3 Binary Tree Node Implement<strong>at</strong>ions 157/** Base class for expression tree nodes */public interface VarBinNode {public boolean isLeaf(); // All subclasses must implement}/** Leaf node */class VarLeafNode implements VarBinNode {priv<strong>at</strong>e String oper<strong>and</strong>;// Oper<strong>and</strong> valuepublic VarLeafNode(String val) { oper<strong>and</strong> = val; }public boolean isLeaf() { return true; }public String value() { return oper<strong>and</strong>; }};/** Internal node */class VarIntlNode implements VarBinNode {priv<strong>at</strong>e VarBinNode left;priv<strong>at</strong>e VarBinNode right;priv<strong>at</strong>e Character oper<strong>at</strong>or;}public VarIntlNode(Character op,VarBinNode l, VarBinNode r){ oper<strong>at</strong>or = op; left = l; right = r; }public boolean isLeaf() { return false; }public VarBinNode leftchild() { return left; }public VarBinNode rightchild() { return right; }public Character value() { return oper<strong>at</strong>or; }// Left child// Right child// Oper<strong>at</strong>or value/** Preorder traversal */public st<strong>at</strong>ic void traverse(VarBinNode rt) {if (rt == null) return;// Nothing to visitif (rt.isLeaf())// Process leaf nodeVisit.VisitLeafNode(((VarLeafNode)rt).value());else {// Process internal nodeVisit.VisitInternalNode(((VarIntlNode)rt).value());traverse(((VarIntlNode)rt).leftchild());traverse(((VarIntlNode)rt).rightchild());}}Figure 5.10 An implement<strong>at</strong>ion for separ<strong>at</strong>e internal <strong>and</strong> leaf node represent<strong>at</strong>ionsusing Java class inheritance <strong>and</strong> virtual functions.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!