如何从存储在数据库中的信息中显示树? [英] How to display a tree from the information stored in database?

查看:155
本文介绍了如何从存储在数据库中的信息中显示树?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用嵌套集,可以在关系数据库中存储树。如何显示树,每个节点的关系是否正确?

Using Nested Sets, it's possible to store a tree in a relational db. How to display the tree, with the correct relations of each node?

例如,每个节点的左右值都存储在db中。如何根据嵌套集数据在java中显示这个树?如何仅使用存储在DB中的信息显示每个节点的正确层次结构和关系?如何显示从根到没有子节点的路径,例如A-> B-> D,A-> C,A-> E-> F.

For example, each node's left and right values are stored in db. How to display this tree in java based on the nested set data? How to display the correct hierarchy and relations of each node only with the information stored in DB? How to display the path from the root to the node which has no children, for instance, A->B->D, A->C, A->E->F.

EIDT:

仅根据表格中的信息,是否可以显示如下树:

Based only on the information in the table, is it possible to display the tree like:

A

---- B

-------- D

--------D

---- C

---- E

-------- F

--------F

谢谢。

推荐答案

假设你有一个课程如下:

Assuming you have a class as follows:

class MyNode
{
    public int id; // these could (should?) be made private with getter/setter methods
    public String value;
    public int lft;
    public int rgt;
}

使用此功能可以执行以下操作:

Using this you could do something like this:

ArrayList<MyNode> nodes = new ArrayList<MyNodes>();
// add SQL code to load values from DB
// make sure to load the nodes sorted by their lft values.
for ( int c = 0; c < nodes.size(); c++ )
{
    String result = createNodeListFor(nodes.elementAt(c), nodes);
    if ( result != null )
    {
        System.out.println(result);
    }
}

缺少方法:

public String createNodeListFor( MyNode endNode, ArrayList<MyNodes> nodes )
{
    String result = "";
    // Again, this assumes the nodes are sorted by 'lft'
    for ( int i = 0; i < nodes.size(); i++ )
    {
        MyNodes current = nodes.elementAt(i);
        if ( current.id == endNode.id )
            continue; // skip self test
        if ( current.lft < endNode.lft && current.rgt > endNode.rgt )
        {
            if ( result == null )
                result = current.value;
            else
                result += "->" + current.value;
            continue;
        }
        if ( current.lft < endNode.lft && current.rgt < endNode.rgt )
        {
            return null; // this node is not an end node
        }
        if ( current.lft > endNode.lft )
        {
            break; // assuming the list is correctly sorted, we don't need to check any more nodes
        }
    }
    return result;
}

这样的事情可能工作......好运气;)

Something like this might work ... good luck ;)

这篇关于如何从存储在数据库中的信息中显示树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆