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

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

在此处输入图像描述

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

EIDT:

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

一个

—-乙

——– d

– – C

—-è

– – – – F

谢谢。

假设你有一个如下课程:

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 nodes = new ArrayList(); // 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 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; } 

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