递归地将节点添加到自定义TreeMap中

时间:2018-11-03 20:21:47

标签: java data-structures

您好,我正在尝试构建自己的TreeMap数据结构。我有一个传递键和值的add方法,然后有另一个称为insert的方法,该方法将节点递归地添加到树中。我不断收到stackoverflow错误。 我不确定如何解决该错误,我已经重写了几次插入方法,并尝试将父节点传递到该方法中。有人可以解释应将哪些内容传递给insert方法的逻辑,或者我的代码可能仍然可以工作吗?

这里是利用递归将节点添加到树中的最佳选择吗?还是可以用while循环完成同一件事?

感谢您的帮助!

public boolean add(K key, V value) 
{

 //root is declared as a class level variable in my Map class 

if (root == null) {

        curSize++;
        root = new Node(key, value);
        root.parent = null;
        return true;
    }
    //Creating a new Node with the passed arguments
    Node n = new Node(key, value);
    Node curNode = root;

//Calling insert method

    if (curNode.insert(n, curNode)) {
        curSize++;
        return true;
    } else {
        return false;
    }
}

protected boolean insert(Node curNode, K key, V value) {

        int result = key.compareTo(curNode.key);
        boolean x = false;

        if (curNode.L == null && result < 0) {
            curNode.L = new Node(key, value);
            x = true;
        }
        if (curNode.R == null && result > 0) {
            curNode.R = new Node(key, value);
            x = true;
        }
        if (result == 0)
            x = false;

        if (curNode.L != null && result < 0)
            insert(curNode.L, key, value);
        if (curNode.R != null && result > 0)
            insert(curNode.R, key, value);

        return x;

    }
//My Node class with its constructor, Insert method is inside this class.

 private class Node {
    public Node L;
    public Node R;
    public K key;
    public V value;
    public Node parent;

    public Node(K k, V v) {
        this.L = null;
        this.R = null;
        this.key = k;
        this.value = v;
    }

2 个答案:

答案 0 :(得分:1)

在您执行insert()时,您拥有

bla->foo

但是,当您调用它时,您会写

(*bla).foo

我想念什么吗?在我看来,这段代码不应该运行。我相信您应该将其称为

insert(Node curNode, K key, V value) 

另外,您有

curNode.insert(n, curNode)

在insert()方法的开头,可以用return语句替换,以避免在成功添加节点后进入递归块。我会将您的插入方法更改为此:

insert(curNode, key, value);

为避免在不需要时意外调用insert()。

答案 1 :(得分:0)

您忘记在以下插入调用中使用返回值:

    if (curNode.L != null && result < 0)
        insert(curNode.L, key, value);
    if (curNode.R != null && result > 0)
        insert(curNode.R, key, value);

应该是:

    if (curNode.L != null && result < 0)
        x = insert(curNode.L, key, value);
    if (curNode.R != null && result > 0)
        x = insert(curNode.R, key, value);

但是请考虑使用return语句消除变量x。