【问题标题】:how to transform an Array to an N-ary tree?如何将数组转换为 N 叉树?
【发布时间】:2014-05-01 13:59:38
【问题描述】:

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

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

Link to image here

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

感谢您的帮助!

[已编辑]

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

【问题讨论】:

    标签: javascript arrays tree transform tree-structure


    【解决方案1】:

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

    Construct a complete K-ary tree from preorder traversal

    【讨论】:

      【解决方案2】:

      这是一个伪代码/ C# 版本。请在 cmets 中询问任何与 C# 相关的问题。这里的关键是使用先进先出数据结构,即下面sn-p 中的队列parentsconvertToN_aryTree 方法返回生成的 n 叉树的根节点。

      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;
      }
      

      【讨论】:

      • 感谢您的回复,但这个算法没有给我正确的节点顺序。看到这张照片:tiikoni.com/tis/view/?id=5f6ae9f 有没有办法以我想要的正确形式重新排序树?非常感谢
      • 您不能仅从给定的数组构造树。原因是这样的。在您的示例中,树表示数组的前序遍历。所以问题是要求构造一棵树,给定一个前序遍历,这是不可能的(geeksforgeeks.org/…)。除了给定的前序遍历之外,我们还需要更多的约束,比如有序遍历。
      • 感谢您的帮助,但我找到了解决方案。我编辑了问题并添加了解决方案!
      • 这很有趣。但是,您可以拥有不同的树,这些树可以从给定的前序遍历中构建。这里的限制可能是树需要完整,这可以通过您发布的解决方案中的(int)ceil( log((double)n*(k-1) + 1 )/log((double)k)) 行来实现。即使有完整性的约束,我也不确定是否可以构造一棵唯一的树。但它看起来像一个可以。
      • 好的,事实证明对于给定的前序遍历有一个唯一的 COMPLETE k-ary 树。这意味着您发布的解决方案将起作用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-17
      • 2022-01-12
      • 2020-09-29
      • 2015-05-07
      • 2015-06-17
      • 2021-12-01
      相关资源
      最近更新 更多