2014-01-15 96 views
1

使用嵌套集合,可以將樹存儲在關係數據庫中。如何顯示樹,每個節點的正確關係?如何從存儲在數據庫中的信息顯示樹?

enter image description here

舉例來說,每一節點的左值和右值被存儲在DB中。如何基於嵌套集合數據在java中顯示這棵樹?如何僅顯示每個節點的正確層次和關係以及存儲在數據庫中的信息?如何顯示從根到沒有子節點的路徑,例如A-> B-> D,A-> C,A-> E-> F。

EIDT:

僅基於在表中的信息,是能夠顯示的樹等:

----乙

---- ---- d

----ç

----ë

-------- F

謝謝。

+0

您是否問如何在屏幕上以圖形方式(或文本方式)顯示?或者如何通過記憶中的某種對象來處理它? – munyul

+0

文字。我的觀點是如何從數據庫中重構樹。 – Way

+0

我不明白你的問題。你想直接在數據庫上進行樹操作,你想對Java對象進行樹操作還是其他的操作? –

回答

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

像這樣的事情可能工作...祝你好運;)

+0

謝謝。我會在稍後嘗試。如何顯示三條路徑:A - > B - > D,A - > C,A - > E - > F? – Way

+0

@Wei,它應該已經這樣做了。只是不在一行(因爲'println'調用)。 – munyul

+0

將數據組織爲嵌套集的原因是直接在SQL中執行樹操作。即已經有一個API來從數據庫中正確構造數據(例如getChildren(nodeId))。 –

相關問題