12.07.2015 Views

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

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

164 Chap. 5 Binary Trees/** Binary tree node implementation: Pointers <strong>to</strong> children */class BSTNode implements BinNode {private Key key;// Key for this nodeprivate E element;// Element for this nodeprivate BSTNode left; // Pointer <strong>to</strong> left childprivate BSTNode right; // Pointer <strong>to</strong> right child}/** Construc<strong>to</strong>rs */public BSTNode() {left = right = null; }public BSTNode(Key k, E val){ left = right = null; key = k; element = val; }public BSTNode(Key k, E val, BSTNode l, BSTNode r){ left = l; right = r; key = k; element = val; }/** Return <strong>and</strong> set the key value */public Key key() { return key; }public void setKey(Key k) { key = k; }/** Return <strong>and</strong> set the element value */public E element() { return element; }public void setElement(E v) { element = v; }/** Return <strong>and</strong> set the left child */public BSTNode left() { return left; }public void setLeft(BSTNode p) { left = p; }/** Return <strong>and</strong> set the right child */public BSTNode right() { return right; }public void setRight(BSTNode p) { right = p; }/** Return true if this is a leaf node */public boolean isLeaf(){ return (left == null) && (right == null); }Figure 5.7 A binary tree node class implementation.As an example of a tree that s<strong>to</strong>res different information at the leaf <strong>and</strong> internalnodes, consider the expression tree illustrated by Figure 5.9. The expressiontree represents an algebraic expression composed of binary opera<strong>to</strong>rs such as addition,subtraction, multiplication, <strong>and</strong> division. Internal nodes s<strong>to</strong>re opera<strong>to</strong>rs,while the leaves s<strong>to</strong>re oper<strong>and</strong>s. The tree of Figure 5.9 represents the expression4x(2x + a) − c. The s<strong>to</strong>rage requirements for a leaf in an expression tree are quitedifferent from those of an internal node. Internal nodes s<strong>to</strong>re one of a small set ofopera<strong>to</strong>rs, so internal nodes could s<strong>to</strong>re either a small code identifying the opera<strong>to</strong>ror a single byte for the opera<strong>to</strong>r’s character symbol. In contrast, leaves must s<strong>to</strong>revariable names or numbers. Thus, the leaf node value field must be considerably

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

Saved successfully!

Ooh no, something went wrong!