# java 实现平层数组转换为层级对象

## sql

```insert into tb_tree (CID, CNAME, PID) values (1, '中国', 0);
insert into tb_tree (CID, CNAME, PID) values (2, '北京市', 1);
insert into tb_tree (CID, CNAME, PID) values (3, '广东省', 1);
insert into tb_tree (CID, CNAME, PID) values (4, '上海市', 1);
insert into tb_tree (CID, CNAME, PID) values (5, '广州市', 3);
insert into tb_tree (CID, CNAME, PID) values (6, '深圳市', 3);
insert into tb_tree (CID, CNAME, PID) values (7, '海珠区', 5);
insert into tb_tree (CID, CNAME, PID) values (8, '天河区', 5);
insert into tb_tree (CID, CNAME, PID) values (9, '福田区', 6);
insert into tb_tree (CID, CNAME, PID) values (10, '南山区', 6);
insert into tb_tree (CID, CNAME, PID) values (11, '密云县', 2);
insert into tb_tree (CID, CNAME, PID) values (12, '浦东', 4);```

## RecursiveTest 递归实现

```package recursive;

import me.shib.java.lib.utils.JsonUtil;

import java.util.List;

public class RecursiveTest {

public static void main(String[] args) {
JsonUtil jsonUtil = new JsonUtil();
RecursiveTest recursive = new RecursiveTest();
jsonUtil.toJson(recursive.recursiveTree(1));

}

/**
* 递归算法解析成树形结构
*
* @param cid
* @return
* @author jiqinlin
*/
public TreeNode recursiveTree(int cid) {
//根据cid获取节点对象(SELECT * FROM tb_tree t WHERE t.cid=?)
TreeNode node = personService.getreeNode(cid);
//查询cid下的所有子节点(SELECT * FROM tb_tree t WHERE t.pid=?)
List<TreeNode> childTreeNodes =personService.queryTreeNode(cid);
//遍历子节点
for (TreeNode child : childTreeNodes) {
TreeNode n = recursiveTree(child.getCid()); //递归
}

//        return node;
return node;
}
}```

## 树的结点类

```package recursive;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class TreeNode implements Serializable {

private Integer cid;
private String cname;
private Integer pid;
private List nodes = new ArrayList();

public TreeNode() {
}

public Integer getCid() {
return cid;
}

public String getCname() {
return cname;
}

public Integer getPid() {
return pid;
}

public List getNodes() {
return nodes;
}

public void setCid(Integer cid) {
this.cid = cid;
}

public void setCname(String cname) {
this.cname = cname;
}

public void setPid(Integer pid) {
this.pid = pid;
}

public void setNodes(List nodes) {
this.nodes = nodes;
}
}```

52 篇文章12 人订阅

0 条评论

## 相关文章

18320

39010

22640

### 聊聊rocketmq的PushConsumerImpl

io/openmessaging/rocketmq/consumer/PushConsumerImpl.java

20020

7630

16010

### nProtect APPGuard安卓反外挂分析

1.最近在学习手游保护方面的技术，本文是学习过程中分析某反外挂的一点记录，高手莫要见笑，有不对的地方还请指教，首先简单通过资源目录中文件名做基本了解，

49400

### FunDA（2）－ Streaming Data Operation：流式数据操作

在上一集的讨论里我们介绍并实现了强类型返回结果行。使用强类型主要的目的是当我们把后端数据库SQL批次操作搬到内存里转变成数据流式按行操作时能更方便、准确、...

22460

### 聊聊HystrixEventNotifier

hystrix-core-1.5.12-sources.jar!/com/netflix/hystrix/strategy/eventnotifier/Hyst...

12820

### Akka（8）： 分布式运算：Remoting-远程查找式

Akka是一种消息驱动运算模式，它实现跨JVM程序运算的方式是通过能跨JVM的消息系统来调动分布在不同JVM上ActorSystem中的Actor进行运算，...

44890