【问题标题】:Adjacency list Sort algorithm邻接表排序算法
【发布时间】:2017-11-06 11:22:19
【问题描述】:

我有这种邻接表:​​

我需要将其排序为: 2、7、9、10、8、16、17、11

基本上,我有一个表格,我在其中存储了带有父 ID 的帖子。我可以有无限数量的关卡。

我只需要 PHP 中的算法或完整代码。

我尝试使用行/列前缀的变体和一些循环函数。

【问题讨论】:

  • 你那里的树看起来很漂亮,但我们为你做这件事还不够好。 Stackoverflow 可以帮助您解决特定的编码问题。如果您自己试一试并解决遇到的任何问题,我们将非常乐意提供帮助;但是“我只需要 php 中的算法或完整代码”表明您什么都没尝试,也没有进行任何研究。
  • 对我来说这看起来不像二叉树。您所拥有的是一个邻接列表 - 有很多关于解析邻接列表的指南(使用 PHP 或伪代码)。
  • @iainn 没有二叉树“分支”,而邻接表只是一条“路”?这在我看来就像一棵二叉树。
  • OP 看看这个人是如何就二叉树提出类似问题的; stackoverflow.com/questions/5020738/…
  • 二叉树中的一个节点只能有左右两个子节点。

标签: php algorithm binary-tree


【解决方案1】:

好吧,我终于做到了。我是 idi*t。

public function makeTree($parent_id = 0, &$array = array())
{
   // Get results where parent_id == $parent_id
  $recepts = $this->recept->get()->where("parent_id =" . $parent_id);
   // Foreach through them
   foreach ($recepts as $recept) {
     // Add this to array
     array_push($array, $recept);
     // Repeat
     $this->makeTree($recept["id"], $array);
   }
   return $array;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-19
    • 2019-07-25
    • 2014-04-01
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 2019-04-10
    • 1970-01-01
    相关资源
    最近更新 更多