二叉搜索树递归插入方法

时间:2017-05-16 09:13:24

标签: java binary-search-tree

我正在研究Java,我有一些问题:

这是binary search tree,我想创建insert方法。我做了什么错了?

我认为leftrightNode,但我不知道如何使用它,因为Node我知道就像

public Node(int data, Node next)

我该怎么做?

public class BST {
private Comparable key;
private BST left, right;

public BST(Comparable key) {
    this.key = key;
    this.left = null;
    this.right = null;
}

public boolean insert(Comparable key) {
    if (key.compareTo(this.key) < 0) {
        if (this.left == null) {
            System.out.println(key + " : insert success");
            this.left = left;
            return true;
        } else {
            insert(key);
        }
    } else if (key.compareTo(this.key) > 0) {
        if (this.right == null) {
            this.right = right;
            System.out.println(key + " : insert success");
            return true;
        } else {
            insert(key);
        }
    }
    System.out.println(key + " : insert fail");
    return false;
}
public static void main(String[] args) {
    BST b = new BST("B");

    System.out.println("========== insert ==========");
    b.insert("G");
    b.insert("D");
    b.insert("K");
    b.insert("A");
    b.insert("D");
    b.insert("J");
    b.insert("H");
    b.insert("C");
    b.insert("A");
    b.insert("F");
    b.insert("E");
    b.insert("N");
}

}

1 个答案:

答案 0 :(得分:0)

you are not doing the insert correctly , when you find the position you need to create a new Node with the new key and make it the leaf, for example in your first check

     if (key.compareTo(this.key) < 0) {
    if (this.left == null) {
        System.out.println(key + " : insert success");
        this.left = new BST(key);
        return true;
    } else {
        return insert(key);
    }

you also need to check if the sent key is already inserted and return true.

相关问题