3.2.47

上次更新:2020-01-29
发现了题解错误/代码缺陷/排版问题?请点这里:如何:提交反馈

解答

如下图所示,内部路径平均长度是比较符合规律的:

方差:

代码

一次测试:

private int Test(int n)
{
    var data = GetRandomInt(n);
    var bst = new BST<int, int>();
    foreach (var d in data)
    {
        bst.Put(d, d);
    }

    return bst.AverageInternalPathLength();
}

求解内部路径长度:

public int AverageInternalPathLength() => InternalPath() / Size() + 1;

private int InternalPath()
{
    var internalPath = 0;
    var nowLayer = new Queue<Node>();
    var nextLayer = new Queue<Node>();
    nextLayer.Enqueue(root);

    var depth = 0;
    while (nextLayer.Count > 0)
    {
        var temp = nowLayer;
        nowLayer = nextLayer;
        nextLayer = temp;

        while (nowLayer.Count > 0)
        {
            var node = nowLayer.Dequeue();
            if (node.Left != null)
            {
                nextLayer.Enqueue(node.Left);
            }

            if (node.Right != null)
            {
                nextLayer.Enqueue(node.Right);
            }

            internalPath += depth;
        }

        depth++;
    }

    return internalPath;
}

另请参阅

BinarySearchTree 库

上一题