使用拆分操作时Treap中的Stackoverflow

时间:2017-05-23 07:37:18

标签: java algorithm data-structures

我正在使用Java制作Treap。

public class Treap {
    private class Pair<T> {
        private T first;
        private T second;

        public Pair(T first, T second) {
            this.first = first;
            this.second = second;
        }

        public T getFirst() {
            return first;
        }

        public T getSecond() {
            return second;
        }
    }

    private int key;
    private int priority;

    private Treap leftSon;
    private Treap rightSon;

    public Treap(int key) {
        this.key = key;
        this.priority = PriorityGenerator.getPriority();
    }

    public Pair<Treap> split(Treap treap, int key) {
        if (treap == null)
            return new Pair<>(null, null);
        if (key > treap.key) {
            Pair<Treap> pair = split(treap.rightSon, key);
            treap.rightSon = pair.first;
            pair.first = treap;
            return pair;
        }
        else {
            Pair<Treap> pair = split(treap.leftSon, key);
            treap.leftSon = pair.second;
            pair.second = treap;
            return pair;
        }
    }
}

问题是split方法有时会导致Stackoverflow异常。但它有时可以正常工作。我真的不明白问题在哪里。有人可以帮我解决这个问题吗?

0 个答案:

没有答案