Building a Java Tree Structure Using Recursive Algorithms and a Database
- Prepare the table structrue and corresponding data a. Table srtucture:
create table TB_TREE
(
CID NUMBER not null,
CNAME VARCHAR2(50),
PID NUMBER //parent node
)
b. Table data:
insert into tb_tree (CID, CNAME, PID) values (1, 'China', 0);
insert into tb_tree (CID, CNAME, PID) values (2, 'Beijing', 1);
insert into tb_tree (CID, CNAME, PID) values (3, 'Guangdong', 1);
insert into tb_tree (CID, CNAME, PID) values (4, 'Shanghai', 1);
insert into tb_tree (CID, CNAME, PID) values (5, 'Guangzhou', 3);
insert into tb_tree (CID, CNAME, PID) values (6, 'Shenzhen', 3);
insert into tb_tree (CID, CNAME, PID) values (7, 'Hai Zhu District', 5);
insert into tb_tree (CID, CNAME, PID) values (8, 'Tian He District', 5);
insert into tb_tree (CID, CNAME, PID) values (9, 'Fu Tian District', 6);
insert into tb_tree (CID, CNAME, PID) values (10, 'Nan Shan District', 6);
insert into tb_tree (CID, CNAME, PID) values (11, 'Mi Yun County', 2);
insert into tb_tree (CID, CNAME, PID) values (12, 'PuDong', 4);
- TreeNode clas corresponding to tb_tree
public class Node implements Serializable {
private Integer id;
private String name;
private Integer parentId;
private List children = new ArrayList();
public Node() {
}
// getters and setters omitted
}
- Test data
public class NodeTest {
@Test
public void loadTree() throws Exception{
System.out.println(JsonUtils.javaToJson(recursiveBuild(1)));
}
/**
* Recursively build a tree structure
*
* @param id
* @return
* @author jiqinlin
*/
public Node recursiveBuild(int id) {
// Retrieve the node object (SELECT * FROM tb_tree t WHERE t.id=?)
Node node = personService.getNode(id);
// Query all child nodes (SELECT * FROM tb_tree t WHERE t.parentId=?)
List childNodes = personService.queryNodes(id);
// Iterate through child nodes
for(Node child : childNodes){
Node n = recursiveBuild(child.getId()); // recursion
node.getChildren().add(n);
}
return node;
}
}
The output JSON format is as follows:
{
"id": 1,
"children": [
{
"id": 2,
"children": [
{
"id": 11,
"children": [],
"name": "Mi Yun County",
"parentId": 2
}
],
"name": "Beijing",
"parentId": 1
},
{
"id": 3,
"children": [
{
"id": 5,
"children": [
{
"id": 7,
"children": [],
"name": "Hai Zhu District",
"parentId": 5
},
{
"id": 8,
"children": [],
"name": "Tian He District",
"parentId": 5
}
],
"name": "Guangzhou",
"parentId": 3
},
{
"id": 6,
"children": [
{
"id": 9,
"children": [],
"name": "Fu Tian District",
"parentId": 6
},
{
"id": 10,
"children": [],
"name": "Nan Shan District",
"parentId": 6
}
],
"name": "Shenzhen",
"parentId": 3
}
],
"name": "Guangdong",
"parentId": 1
},
{
"id": 4,
"children": [
{
"id": 12,
"children": [],
"name": "PuDong",
"parentId": 4
}
],
"name": "Shanghai",
"parentId": 1
}
],
"name": "China",
"parentId": 0
}