How to display a tree from the information stored in database?

可紊 提交于 2019-12-23 04:19:10

问题


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?

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

----C

----E

--------F

Thanks.


回答1:


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

The missing method:

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



来源:https://stackoverflow.com/questions/21141099/how-to-display-a-tree-from-the-information-stored-in-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!