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

执行 arotateL后跟 arotateR最终什么都不做,因为您正在修改同一个节点。n不是原来的n。它是newNodefrom 函数。所以基本上,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 回答