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 159/** Base class: Composite */public interface VarBinNode {public boolean isLeaf();public void traverse();}/** Leaf node: Composite */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>; }public void traverse() {Visit.VisitLeafNode(oper<strong>and</strong>);}/** Internal node: Composite */class VarIntlNode implements VarBinNode { // Internal nodepriv<strong>at</strong>e VarBinNode left;// Left childpriv<strong>at</strong>e VarBinNode right;// Right childpriv<strong>at</strong>e Character oper<strong>at</strong>or;// Oper<strong>at</strong>or value}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; }public void traverse() {Visit.VisitInternalNode(oper<strong>at</strong>or);if (left != null) left.traverse();if (right != null) right.traverse();}/** Preorder traversal */public st<strong>at</strong>ic void traverse(VarBinNode rt) {if (rt != null) rt.traverse();}Figure 5.11 A second 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 using the compositedesign p<strong>at</strong>tern. Here, the functionality of traverse is embedded into the nodesubclasses.

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

Saved successfully!

Ooh no, something went wrong!