修改后的先序树遍历——寻找下一个节点

发布于 2024-08-14 06:02:57 字数 582 浏览 2 评论 0原文

我有这个数据:

id | parent_id | lft | rgt | name
=====================================
1  | 0         | 1   | 8   | abc
2  | 3         | 5   | 6   | jkl
3  | 1         | 2   | 3   | def
4  | 0         | 9   | 10  | mnno
5  | 1         | 4   | 7   | ghi

我需要按这个顺序遍历这个层次结构(ids):1> 3> 5> 2> 4

我怎样才能实现这一目标?

假设我想找到node_x的下一个节点。

if (node_x_rgt - node_x_lft == 1) {
    next_node_lft = node_x_rgt + 1;
} else {
    next_node_lft = node_x_lft + 1;
}

此公式仅在某些情况下有效(节点 ID 1,3,5,2)。节点 2 的下一个节点应该是 4。

I have this data:

id | parent_id | lft | rgt | name
=====================================
1  | 0         | 1   | 8   | abc
2  | 3         | 5   | 6   | jkl
3  | 1         | 2   | 3   | def
4  | 0         | 9   | 10  | mnno
5  | 1         | 4   | 7   | ghi

I need to traverse this hierarchy in this order (ids): 1 > 3 > 5 > 2 > 4

How can I achieve this?

Assume that I want to find the next node of node_x.

if (node_x_rgt - node_x_lft == 1) {
    next_node_lft = node_x_rgt + 1;
} else {
    next_node_lft = node_x_lft + 1;
}

This formula works only in some cases (node ids 1,3,5,2). The next node of node 2 should be 4.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧街凉风 2024-08-21 06:02:57

根据您提供的信息,我所能建议的就是尝试:

select * from table order by id

顺便说一句,id 4 的 lft 和 rgt 列位于树之外,看起来像一个错误?

顺便说一句,如果这是家庭作业,请这样标记。

编辑:问题的版本2:

这些类型的树对于所有节点都具有 (lft < rgt) 不变性。如果表仅包含 1 个根节点,则可以通过 lft 或 rgt 值检索序列,在这种情况下,lft 仍然可以解决问题(但按降序通过 rgt 的替代方案则不会):

select * from table order by lft

With the information you gave all I can advice is to try:

select * from table order by id

btw, the lft and rgt columns for id 4 are outside of the tree, looks like an error?

btw2, if this is homework, please tag it as such.

Edit: version 2 of the question:

These kinds of trees have as invariant that (lft < rgt) for all nodes. If the table contains only 1 root node, sequences can be retrieved by either lft or rgt values, in this case lft still does the trick (but the alternative through rgt in descending order won't):

select * from table order by lft
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文