SUNY Geneseo Department of Computer Science
{Date}
CSci 240, Spring 2007
Prof. Doug Baldwin
Tree lab?
Sections 13.3.3 and 13.3.4
Our own examples
Code
class OrderedBinaryTree { // tree of ints
private int root; // == -1 for empty tree
private OrderedBinaryTree left, right;
boolean isEmpty() {
...
}
int countOccurrences( int x ) {
if ( ! this.isEmpty() ) {
if ( x < root ) {
return left.countOccurrences( x );
}
else if ( x == root ) {
return right.countOccurrences( x ) + 1; }
else { // x > root
return right.countOccurrences( x );
}
}
else {
return 0;
}
}
OrderedBinaryTree insert( int x ) {
if ( ! this.isEmpty() ) {
if ( x < root ) {
left = left.insert( x );
return this;
}
else { // x >= root
right = right.insert( x )
return this;
}
}
else {
return new OrderedBinaryTree( x );
}
}
Efficiency of binary tree algorithms
Read Section 13.3.5