简体   繁体   English

关于Java中的树实现-问题

[英]Regarding Tree Implementation in Java - Question

I want to implement a Generic Tree in java and i want to use a single table for the same.where the structure of the table is as below. 我想在Java中实现泛型树,并且我想对同一个表使用单个表,其中表的结构如下。

public class MyTreeNode {    
  private int id;    
  private int parentId;    
  private MyTreeNode parent;   
  private List<MyTreeNode> childNodes;   
  // further fields..  
}
NAME OF TABLE IS **TREE_TABLE**  
PK_ID       | PARENT  
----------  |----------  
1           | null  
2           | 1  
3           | 1  
4           | 2

Meaning, the nodes with PK_ID 2 and 3 have node 1 as parent, 4 has 2 as parent, and 1 has no parent (null). 这意味着,具有PK_ID 2和3的节点具有节点1作为父节点,4具有2作为父节点,而1没有父节点(空)。

how to implement this in Java code.Any sample code if you have for this or if you can share the code,Please Share it across. 如何在Java代码中实现此代码。如果您有此示例代码,或者可以共享代码,请共享。

Requirement: Access the above table from underlyng SQL server database and rebuild the tree structure such that the relationship between Parent and Child are set. 要求:从底层SQL Server数据库访问上表,并重建树结构,以便设置父级和子级之间的关系。

Regards Deepak 问候迪帕克

Put all your Nodes in an arrayList, created by order. 将所有节点放入按顺序创建的arrayList中。 This algorithm assumes the get the table rows by order of PK_ID. 该算法假定按PK_ID的顺序获取表行。

nodes = emptyArrayList

for each row in your table:
   node n = new Node(PK_ID)
   nodes.add(n)
   if (PARENT != null)
       nodes.get(PARENT).addChild(n)

after that, nodes[0] is the root of your tree. 之后,nodes [0]是树的根。 I'm not going to show you how to create a tree data structure. 我不会向您展示如何创建树数据结构。

EDIT: about the tree 编辑:关于树

As for your tree, each node should only know about the nodes under it, not above. 至于树,每个节点应该只知道其下的节点,而不是上面的节点。 So your parent id and parent node fields aren't needed. 因此,不需要您的父ID和父节点字段。 Otherwise, it looks good. 否则,看起来不错。

EDIT: More about your tree structure: 编辑:有关您的树结构的更多信息:

As I said, your tree structure is fine. 如我所说,您的树结构很好。 It can just be a class with an id and the list of children nodes. 它只能是具有ID和子节点列表的类。 That's all you need. 这就是您所需要的。

The basics on doing a tree in OO languages: 用OO语言制作树的基础知识:

  • You'll need some type of a Node class to hold the data and references to (parents, children, siblings, etc - depending on implementation) 您将需要某种类型的Node类来保存数据和对其的引用(父,子,兄弟姐妹等-取决于实现)

  • When dealing with trees, recursion is your friend. 与树木打交道时,递归是您的朋友。

I would use a HashMap : 我会使用HashMap

HashMap<Integer, Integer> table = new HashMap<Integer, Integer>();

table.put(1, null);
table.put(2, 1);
table.put(3, 1);
table.put(4, 2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM