2

我有一个数组,需要将其转换为 N 叉树。我知道 N 的值和节点的总数。

我在下图中给你一个例子。N 叉树应该如图所示排序。

链接到这里的图片

我想不通。我需要一个算法来做到这一点。我正在编写的程序是用 javascript 编写的,但伪代码的答案也很好。

感谢你的帮助!

[已编辑]

我从这里找到了使用算法的解决方案:Construct a complete K-ary tree from preorder traversal

4

2 回答 2

2

我从这里找到了使用算法的解决方案:

从前序遍历构造一个完整的 K-ary 树

于 2014-06-04T09:42:28.403 回答
0

Here is a pseudo code/ C# version. Please ask any C# related questions in comments. The key thing here is use of a first-in-first-out data structure, the queue parents in the snippet below. The method convertToN_aryTree returns root node of the resulting n-ary tree.

public class Node
{
    public int data;
    public int nCount; // 'n' in n-ary
    public Node[] children; // this needs to be initialised to length n

    public Node(int d, int n)
    {
        data = d;
        nCount = n;
        children = new Node[n];
    }
}

// data is teh array and n is branch factor of the tree
Node convertToN_aryTree(int[] data, int n)
{
    if(data.Length == 0)
    {
        return null;
    }
    Node root = new Node(data[0], n);
    Node currParent = root;
    Node curr;
    int currChildCount = 0;
    Queue<Node> parents = new Queue();
    for(int i = 1; i<data.Length; i++)
    {
        curr = new Node(data[i], n);
        currParent.children[currChildCount] = curr;
        parents.Enqueue(curr);

        currChildCount++;
        if(currChildCount >= n) // finished with children of this node, so start adding to children of the next.
        {                       // next node is either a sibling or a child but that is taken care of by Queue.
            currParent = parents.Dequeue();
            currChildCount = 0;
        }
    }

    return root;
}
于 2014-05-01T14:21:56.593 回答