Question

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?

enter image description here

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.

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top