Finding Node with biggest value on level lev (Java, BST)

Viewed 34

I need to write a method T bigOnLevel(int lev) that finds the node with the biggest value on the level lev. Since I'm new to java generics, I'm getting issues with the T. My idea is to compare the height of the rightChild/leftChild subtree with lev so I know if a node exists on that level in the subtree:

if(!rightChild.isEmpty() && rightChild.bigOnLevel(lev) >= lev)

I'm getting the error bad operand types for binary oeprator >= first type T second type int. But without being allowed to compare them to each other I can't think of another way to find the node with the biggest value.

The entire Code(method at the end):

public class BinarySearchTree<T extends Comparable<T>> {
private T content;
private BinarySearchTree<T> leftChild, rightChild;

public BinarySearchTree() {
    content = null;
    leftChild = null;
    rightChild = null;
}

public T getContent() {
    if (!isEmpty()) {
        return content;
    } else {
        throw new RuntimeException();
    }
}

public boolean isEmpty() {
    return content == null;
}

public boolean isLeaf() {
    return !isEmpty() && leftChild.isEmpty() && rightChild.isEmpty();
}

public void add(T t) {
    if (isEmpty()) {
        content = t;
        leftChild = new BinarySearchTree<T>();
        rightChild = new BinarySearchTree<T>();
    } else {
        if (content.compareTo(t) > 0) {
            leftChild.add(t);
        } else if (content.compareTo(t) < 0) {
            rightChild.add(t);
        }
    }
}

public boolean contains(T t) {
    if (isEmpty()) {
        return false;
    } else {
        if (content.compareTo(t) > 0) {
            return leftChild.contains(t);
        } else if (content.compareTo(t) < 0) {
            return rightChild.contains(t);
        }
        return true;
    }
}

public int size() {
    if (isEmpty()) {
        return 0;
    } else {
        return 1 + leftChild.size() + rightChild.size();
    }
}

public void show() {
    if (!isEmpty()) {
        leftChild.show();
        System.out.println(content);
        rightChild.show();
    }
}


//Program:

public T bigOnLevel (int lev)
{
    int currentlevel = 0;
    if(isEmpty()  || lev<0 )
    {
        return null;
    }
    else
    {
        if(currentlevel < lev)
        {
            currentlevel++;
            if(!rightChild.isEmpty() && rightChild.bigOnLevel(lev) >= lev)
            {
                return rightChild.bigOnLevel(lev);
            }
            else
            {
                if(!leftChild.isEmpty() && leftChild.bigOnLevel(lev) >= lev)
                {
                    return leftChild.bigOnLevel(lev);
                }
                else
                {
                    return null;
                }
            }
        }
        else
        {
            return content;
        }
    }
}

}

0 Answers
Related