推动 NestedSet 创建平衡树
我正在尝试使用 Propel 的 NestedSet 功能。但是,我缺少一些有关插入的内容,以便树在创建时保持平衡(即水平填充)。
假设我有这些元素:
root
r1c1 r1c2
r2c1 r2c2
我想插入 r2c3 作为 r1c2 的第一个子元素(即在开始第 3 行之前填充第 2 行)。
我的第一个尝试是创建这个函数:
function where(User $root,$depth=0)
{
$num = $root->getNumberOfDescendants();
if ( $num < 2 )
return $root;
foreach($root->getChildren() as $d)
{
if ( $d->getNumberOfChildren() < 2 )
{
return $d;
}
}
foreach($root->getChildren() as $d)
{
return where($d, $depth+1);
}
}
但是,这将在 r2c1 上插入一个子项,而不是像我想要的那样在 r1c2 上插入一个子项。
有没有办法以某种方式将条目插入树中的下一个可用位置?
TIA 麦克风
I'm trying to use Propel's NestedSet feature. However, I'm missing something about inserting such that the tree is balanced as it is created (i.e. fill it in horizontally).
Say I have these elements:
root
r1c1 r1c2
r2c1 r2c2
I want to insert r2c3 as the 1st child of r1c2 (i.e. fill row 2 before starting on row 3).
My first stab at this was to create this function:
function where(User $root,$depth=0)
{
$num = $root->getNumberOfDescendants();
if ( $num < 2 )
return $root;
foreach($root->getChildren() as $d)
{
if ( $d->getNumberOfChildren() < 2 )
{
return $d;
}
}
foreach($root->getChildren() as $d)
{
return where($d, $depth+1);
}
}
However, this will insert a child on r2c1, rather at r1c2 as I want.
Is there a way to insert an entry into the tree at the next available spot somehow?
TIA
Mike
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好的,感谢 http://mikehillyer.com/articles/managing-hierarchical -data-in-mysql/,我发现这个算法会做我想要的事情:
它基本上执行这个SQL:
叶子有RIGHT=LEFT+1,有1个子节点的节点有RIGHT=LEFT+3。通过添加 ORDER BY u.PARENT_ID,我们找到树中可用的最高节点。如果使用 LEFT_ID 或 RIGHT_ID,则不会平衡树。
OK, thanks to http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/, I found that this algorithm will do what I want:
It basically executes this SQL:
A leaf has RIGHT=LEFT+1, A node with 1 child has RIGHT=LEFT+3. By adding the ORDER BY u.PARENT_ID, we find the highest node in the tree available. If you use LEFT_ID or RIGHT_ID, it does not balance the tree.