2017-03-18 81 views
0
    StorageRoom 
        /  \ 
        /  \ 
       /   \ 
        "A"   "B" 
       /\  /\ 
       / \  / \ 
       "0" "1"  "0" "1" (node at this level has 3 children) 
      /| \ 
      /| \    ==== 
           each node at this level has four children 
      "0" "1" "2"   ==== 
      /|\ \ 
     /| \ \    

    "0" "1" "2" "3"   
     | | | | 
    Obj1 Obj2 Obj3 Obj4 

底層有不同的類型(不是字符串),在Java中爲這種類型的數據選擇和實現的最佳數據結構是什麼?

此外,考慮到可以發散在今後更廣泛,更多的孩子,和節點和每個級別可能會有所不同。

目前;我在想嵌套的hashMap,樹。但我想不出一種遞歸構建這種數據結構的方法。 構建地圖;我們將給出每個級別的名稱(字符串)和數字(int)。像{「AB」,「01」,「012」,「0123」,Object}這樣我們可以建立這樣的結構

另外;我需要一個實現,以便在給出對象時返回路徑(從根目錄到目標)

同時,給定一條路徑;快速返回對象。我目前的想法:

public class StorageRoom<T> { 

    String name; //name for the node 
    LinkedList<StorageRoom<T>> children; 
    LinkedList<Product> product; // represents the bottom level where children is a product 

    public StorageRoom(String name, LinkedList children) { 
    this.name = name; 
    this.children = children 
    } 


    public StorageRoom(String name, LinkedList product) { //represents the bottom level child 
    this.name = name; 
    this.product = product 
    } 

} 

但我不知道如何建立這樣的結構遞歸。

+0

有一個孩子而不是孩子的數組鏈接列表可能是一個很好的開始。你怎麼看。 – Shubham

+0

您的使用示例不清楚。編寫說明結構如何初始化和使用的實際代碼。然後我們可以給你更好的想法如何定義它的內部。 – erickson

+0

這就是每個級別都有固定節點數的樹。不應該太難以實現。其餘的只是普通的舊遞歸。如果您希望獲得有用的答案,您應該縮小實際問題的範圍。即這棵樹用於/爲什麼這個結構是什麼? – Paul

回答

-1

你可以建立一個節點結構像下面這樣:

class Node<T> { 
    T value; 
    List<Node<?>> children; 
} 

然後你可以使用一個樹狀結構下面的一個:

class Tree { 
    Node<String> root; 

    Node<?> findNode(String path); 
    void addNode(Node<?> newNode); 
    void validate(Node<?> node, int level); 
    // All other tree operations go here 

} 

最重要的方法,你需要添加意志是根據路徑搜索節點,然後驗證並向樹添加新節點。所有這些將進入Tree數據結構。


希望這有助於!

+0

爲什麼選擇投票?最初的問題是提出一個我所做過的數據結構。如果問題稍後被編輯以詢問不同的事情,這是否使我的答案不值得? – anacron

+0

感謝您的回覆;現在是這樣;我很難製造這樣一棵樹;我能想到的唯一方法是使用嵌套循環(可能四個);我想不出遞歸的方式;任何提示都可能有幫助 – ElleryL

+0

有兩種方法可以構建樹。一個使用文件或某個數據庫中的現有數據從用戶或另一個輸入。爲了創建節點,您可能不需要遞歸。遞歸將在'find'方法內部實現。 – anacron

相關問題