【问题标题】:Computing the height of a tree C#计算树的高度 C#
【发布时间】:2018-11-24 18:30:24
【问题描述】:

我一直在编写这段代码,用于在 C# 中计算树的高度。这个问题的输入首先是:节点的数量,然后是每个节点的数量。那么输出将是树的高度。

输入

5

4 -1 4 1 1

输出 3

 public long Solve(long nodeCount, long[] tree)
    {
        List<long>[] Node = new List<long>[nodeCount];
        long root = 0; 

        for(int i =0;i<nodeCount;i++ )
        {
            Node[i] = new List<long>();
        }

        for(int j =0; j<nodeCount;j++)
        {
            if (tree[j] == -1)
                root = j;
            else
                Node[tree[j]].Add(j);
        }

        Queue<long> Q = new Queue<long>();
        Q.Enqueue(root);
        long Height = 0;

        while(Q.Any())
        {

            for(int i =0; i<Q.Count(); i++)
            {
                long nodee = Q.Dequeue();

                if(Node[nodee] != null)
                {
                    foreach(long N in Node[nodee])
                    {
                        Q.Enqueue(N);
                    }
                }
            }

           Height = Height+1;
        }
        return Height;
    }

此代码向我的测试用例返回错误结果。有什么问题?

【问题讨论】:

  • @Disaffected1070452 由于某种原因,我无法调试
  • 您的 Visual Studio 是进入调试模式还是发布模式?
  • 一棵树怎么可能是一个数组(long[] 树)?树不应该是根节点吗?每个节点都有一个左和右。要获得高度,您必须横穿节点并找到从根到叶的最大节点数。
  • @jdweng 这看起来像一棵扁平的树,其中每个元素的值都指向其父元素的索引。
  • 只有在每个元素都有树的情况下才有效。如果一个节点只有一个孩子会怎样?

标签: c# tree binary-tree


【解决方案1】:

当使用2个数组(作为索引节点的2个子节点的指针)时,您可以交换O(n)中树节点的指针方向:

int size = 5;
int arr[size] = {4, -1, 4, 1, 1};
int a[size];
int b[size];
for (int i = 0; i < size; i++) {
    a[i] = -1;
    b[i] = -1;
} // I'm not c++ expert (I guess there are better way of init array with the same value...
int root = -1;
for (int i = 0; i < size; i++) {
    if (arr[i] == -1)
        root = i;
    else if (a[arr[i]] != -1)
        b[arr[i]] = i;
    else 
        a[arr[i]] = i;
}

这是在 1 个 for 循环中完成的。

您现在可以使用这 2 个数组以递归方式获取高度:

int findHeight(int current, int count, int a[], int b[]) {
    int maxV = count;
    if (a[current] > -1)
        maxV = max(findHeight(a[current], count + 1, a, b), maxV);
    if (b[current] > -1)
        maxV = max(findHeight(b[current], count + 1, a, b), maxV);
    return maxV;
} 

执行此操作:

int height = findHeight(root, 1, a, b); //(as root is the first level)

总运行时间复杂度为O(n)

希望有所帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-08
    • 1970-01-01
    • 1970-01-01
    • 2014-02-18
    • 2022-01-25
    • 1970-01-01
    相关资源
    最近更新 更多