如何从存储在数据库中的信息中显示树?

问题描述 投票:1回答:1

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

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

EIDT:

仅基于表中的信息,是否可以显示如下树:

一个

----乙

-------- d

- - C

----è

- - - - F

谢谢。

java tree nested-sets
1个回答
0
投票

假设你有一个如下课程:

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

使用它你可以做这样的事情:

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

这样的事可能有用......祝你好运;)

© www.soinside.com 2019 - 2024. All rights reserved.