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.
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).
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.
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.
Regards
Deepak
Put all your Nodes in an arrayList, created by order. This algorithm assumes the get the table rows by order of PK_ID.
after that, nodes[0] is the root of your tree. 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. 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. That’s all you need.