You are on page 1of 4

Recursion

private void countUp(int n) {


if (n > 0) {
countUp(n - 1);
System.out.print(n + " ");
}
}
private void displayBackward(int n) {
if (n >= 0) {
System.out.println(arrLst[n]);
displayBackward(n - 1);
}
}
private boolean isPrime(int n) {
return isPrime(n, n - 1);
}
private boolean isPrime(int n, int divisor) {
if (divisor > 1 && n % divisor != 0) {
return isPrime(n, divisor - 1);
} else {
return divisor == 1;
}
}
private void convertToBinary(int n) {
if (n > 0) {
convertToBinary(n / 2);
System.out.print(n % 2);
}
}
private int fibonacci(int n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}

Binary Search Tree


public T getEntry(T entry) {
return findEntry(root, entry);
}
private T findEntry(BinaryNode rootNode, T entry) {
T result = null;
if (rootNode != null) {
T rootEntry = rootNode.data;
if (entry.equals(rootEntry))
result = rootEntry;
else if (entry.compareTo(rootEntry) < 0)
result = findEntry(rootNode.left, entry);
else
result = findEntry(rootNode.right, entry);
}
return result;
}
public T add(T newEntry) {
T result = null;
if (isEmpty())
root =new BinaryNode(newEntry);
else
result = addEntry(root, newEntry);
return result;
}
private T addEntry(BinaryNode rootNode, T newEntry) {
T result = null;
int comparison = newEntry.compareTo(rootNode.data);
if (comparison == 0) {
result = rootNode.data;
rootNode.data = newEntry;
}
else if (comparison < 0) {
if (rootNode.left != null)
result = addEntry(rootNode.left, newEntry);
else
rootNode.left = new BinaryNode(newEntry);
}
else {

if (rootNode.right != null)
result = addEntry(rootNode.right, newEntry);
else
rootNode.right = new BinaryNode(newEntry);
}
return result;
public T remove(T entry) {
ReturnObject oldEntry = new ReturnObject(null);
BinaryNode newRoot = removeEntry(root, entry, oldEntry);
root = newRoot;
return oldEntry.get();
}
private BinaryNode removeEntry(BinaryNode rootNode, T entry,
ReturnObject oldEntry){
if (rootNode != null) {
T rootData = rootNode.data;
int comparison = entry.compareTo(rootData);
if (comparison == 0) {
oldEntry.set(rootData);
rootNode = removeFromRoot(rootNode);
}
else if (comparison < 0) {
BinaryNode leftChild = rootNode.left;
rootNode.left = removeEntry(leftChild, entry,
oldEntry);
}
else {
BinaryNode rightChild = rootNode.right;
rootNode.right = removeEntry(rightChild, entry,
oldEntry);
} // end if
} // end if
return rootNode;
}

You might also like