Edit: !!! I posted the wrong code I updated it with the code I am having problems with.
Exception in thread "main" java.lang.NullPointerException at BinarySearchTree.numGreaterThan(BSTEnhanced2.java:41) at BSTEnhanced.main(BSTEnhanced2.java:113)
class BinaryTreeNode {
int element;
BinaryTreeNode left;
BinaryTreeNode right;
int size;
public BinaryTreeNode(int theElement) {
element = theElement;
left = null;
right = null;
size = 1;
}
}
class BinarySearchTree {
BinaryTreeNode root;
public BinarySearchTree(){
root = null;
}
public boolean search(int theElement)
{
BinaryTreeNode x = root;
while (x != null) {
if (x.element == theElement) return true;
if (x.element < theElement) x = x.right;
else x = x.left;
}
return false;
}
public int numGreaterThan(int x){
int counter = 0;
BinaryTreeNode y = root;
while(y != null) {
if (y.element == x){
counter = counter + y.right.size;
}
if (y.element > x){
counter = counter + y.right.size;
counter = counter++;
y = y.left;
}
if (y.element < x){
y = y.right;
}
}
return counter;
}
public void insert(int theElement)
{
if (search(theElement)) return;
if (root == null) {
root = new BinaryTreeNode(theElement);
return;
}
BinaryTreeNode x = root;
boolean done = false;
while (! done) {
x.size = x.size + 1;
if (x.element == theElement) return;
if (x.element < theElement) {
if (x.right == null)
{
x.right = new BinaryTreeNode(theElement);
done = true;
}
else
{ x = x.right; }
}
else {
if (x.left == null) {
x.left = new BinaryTreeNode(theElement);
done = true;
}
else
{ x = x.left;}
}
}
}
public void printTree(){
print(root);
}
public void print(BinaryTreeNode x) {
if (x != null) {
print(x.left);
System.out.println(x.element + " : " + x.size);
print(x.right);
}
}
}
class BSTEnhanced {
public static void main(String [] args) {
BinarySearchTree myTree = new BinarySearchTree();
int e;
for (int i = 0; i < 10; i++) {
e = (int) (20 * Math.random());
myTree.insert(e);
System.out.println(e);
}
myTree.printTree();
for (int i = 0; i < 10; i ++) {
e = (int) (20 * Math.random());
int result = myTree.numGreaterThan(e);
System.out.println("Nodes Greater than " + e + " = " +result);
}
}
}
This post has been edited by shadowdemon69: 27 March 2009 - 08:51 PM

New Topic/Question
Reply




MultiQuote




|