用Java创建通用二进制搜索树

时间:2013-11-13 03:42:40

标签: java data-structures tree nodes

我正在尝试用Java创建这个树但是卡住了,无法弄清楚如何继续。这是我到目前为止的代码:

public class BTNode<E>
{
private E data;
private BTNode<E> left;
private BTNode<E> right;

public BTNode(E newData, BTNode<E> newLeft, BTNode<E> newRight)
{
    setData(newData);
    setLeft(newLeft);
    setRight(newRight);
}

public E getData()
{
    return data;
}

public BTNode<E> getLeft()
{
    return left;
}

public BTNode<E> getRight()
{
    return right;
}

public void inorderPrint()
{
    if(left != null)
        left.inorderPrint();

    System.out.println(data);

    if(right != null)
        right.inorderPrint();
}

public void setData(E newData)
{
    data = newData;
}

public void setLeft(BTNode<E> newLeft)
{
    left = newLeft;
}

public void setRight(BTNode<E> newRight)
{
    right = newRight;
}

}

public class Tree<E extends Comparable<E>>
{
private BTNode<E> root;
private int manyNodes;

public Tree()
{

}

public void add(E element)
{
    BTNode<E> newLeft = null;
    BTNode<E> newRight = null;

    if(root == null)
        root = new BTNode<E>(element, newLeft, newRight);

    else
    {
        BTNode<E> cursor = new BTNode<E>(element, newLeft, newRight);
        cursor = root;
        boolean done = false;

        while(done = false)
        {
            if (element.compareTo(cursor.getData()) <= 0)
            {
                if(cursor.getLeft() == null)
                {
                    cursor.setLeft(element); //create a new node from left
                    done = true;
                }

                else
                    cursor = cursor.getLeft();
            }

            else
            {
                if(cursor.getRight() ==null)
                {
                    cursor.setRight(element); //create a new node from right
                    done = true;
                }
                else
                    cursor = cursor.getRight();
            }
        }
    }

}

public int size()
{
    return manyNodes;
}

public BTNode<E> getRoot()
{
    return root;
}

}

问题是创建左右节点,它不让我,因为类型不同。此外,我不确定在Tree构造函数中放置什么。

1 个答案:

答案 0 :(得分:1)

方法

public void setLeft(BTNode<E> newLeft) {
    left = newLeft;
}
public void setRight(BTNode<E> newRight) {
    right = newRight;
}

期待BTNode个对象,但您将其称为

cursor.setLeft(element); 

其中element的类型为E,而E就编译器而言是一种扩展Comparable<E>的类型。您的类型不匹配。将element包裹在BTNode对象中并传递。{/ p>