假設你有一個類,如下所示:
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;
}
像這樣的事情可能工作...祝你好運;)
您是否問如何在屏幕上以圖形方式(或文本方式)顯示?或者如何通過記憶中的某種對象來處理它? – munyul
文字。我的觀點是如何從數據庫中重構樹。 – Way
我不明白你的問題。你想直接在數據庫上進行樹操作,你想對Java對象進行樹操作還是其他的操作? –