二进制搜索树平衡

时间:2010-03-23 18:57:26

标签: binary-tree binary-search

我在这里有一个问题,但它没有保存。我无法平衡完全不平衡的树(右侧的节点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;
        }
    }

1 个答案:

答案 0 :(得分:1)

执行rotateL后跟rotateR会因为您修改同一节点而无法执行任何操作。 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(...)的实现吗?

相关问题