1

ここで質問がありましたが、保存されませんでした。完全にバランスの取れていないツリー (右側のノード 1 ~ 15) のバランスをとるのに問題があります。

スタックオーバーフローが発生して困っています。

> // balancing
    public void balance(node n) {
        if(n != null) {
            System.out.println(height(n)-levels);
            if (height(n.RCN) != height(n.LCN)) {
                if (height(n.RCN) > height(n.LCN)) {
                    if(height(n.RCN) > height(n.LCN)) {
                        n = rotateL(n);
                        n = rotateR(n);
                    } else {
                        n = rotateL(n);
                    }
                } else {
                    if(height(n.LCN) > height(n.RCN)) {
                        n = rotateR(n);
                        n = rotateL(n);
                    } else {
                        n = rotateR(n);
                    }
                }
                balance(n.LCN);
                balance(n.RCN);
            }
        }
    }

    // depth from node to left
    public int heightL(node n) {
        if (n == null)
            return 0;
        return height(n.LCN) + 1;
    }

    // depth from node from the right
    public int heightR(node n) {
        if (n == null)
            return 0;
        return height(n.RCN) + 1;
    }

    // left rotation around node
    public node rotateL(node n) {
        if (n == null)
            return null;
        else {
            node newRoot = n.RCN;
            n.RCN = newRoot.LCN;
            newRoot.LCN = n;
            return newRoot;
        }
    }

    // right rotation around node
    public node rotateR(node n) {
        if (n == null)
            return null;
        else {
            node newRoot = n.LCN;
            n.LCN = newRoot.RCN;
            newRoot.RCN = n;
            return newRoot;
        }
    }
4

1 に答える 1

1

a のrotateL後に arotateRを実行しても、同じノードを変更しているため、何も実行されません。nオリジナルではありませんn。関数newNodeからです。基本的にnは、次のようなものです。

newNode = rotateL(n);
n = rotateR(newNode);

したがって、基本的にツリーを変更せずに残します。

if (height(n.RCN) > height(n.LCN))チェックを繰り返す理由もわかりません。abs(height(n.RCN) - height(n.LCN)) > 1最初のチェックをより似たものにしてから、比較を使用して回転する方法を決定することを意味していたと思います。

また、の実装を追加していただけheight(...)ますか?

于 2010-03-23T19:35:42.723 に答える