树是一种非散列数据结构,和非散列表一样,它对于存储需要快速查找的数据非常有用。
树是一种分层数据的抽象模型。现实生活中最常见的树的例子是家谱,或是公司的组织架构
本文将讲述一个实例,构造一棵树来实现数组和tree的相互转换,这在前端树结构中是经常遇到的。
将数组转化树结构,并将树结构转化为数组
const list= [
{ id: 1001, parentId: 0, name: 'AA' },
{ id: 1002, parentId: 1001, name: 'BB' },
{ id: 1009, parentId: 1005, name: 'II' },
{ id: 1003, parentId: 1001, name: 'CC' },
{ id: 1004, parentId: 1003, name: 'DD' },
{ id: 1005, parentId: 1003, name: 'EE' },
{ id: 1006, parentId: 1002, name: 'FF' },
{ id: 1007, parentId: 1002, name: 'GG' },
{ id: 1008, parentId: 1004, name: 'HH' },
];
数组list是无规则排序的,不过分析过后,可以看到是一个通过parentId关联的树,那么如何实现呢?
树结构是一个对象,有一个root节点,并且有一系列的方法,比如插入节点,删除节点,获取节点,获取深度等等。
节点也是一个对象,有一定的属性,而且节点的属性也可能是其他的树。
那么我们可以先构造一个节点对象Node,每个Node有id, parentId, name, childNodes属性
构造一棵树listTree,先在数组中找到根节点(parentId === 0)
再给listTree添加list数组中的元素,直到添加完毕,就得到了树结构
class Node {
constructor(options){
let { id, parentId, name } = options
this.id = id || null;
this.parentId = parentId;
this.name = name || null;
this.childNodes = []
}
getId(){
return this.id;
}
...
}
创建listTree时,初始化this.root,生成this.root(generateRoot)
由于在root上添加节点,所以增加了insertNode方法,插入时要找到root中对用的parentId
代码如下:
class listTree{
constructor(arr){
this.root = new Node(arr.find(item => item.parentId === 0))
this.generateRoot(arr)
}
generateRoot(arr){
// ...
}
getNodeById(id){
// ...
}
insertNode(node, id){
let targetNode = this.getNodeById(id)
// ...
}
// ...
}
getNodeById(id):遍历this.root,找到对应元素,这里采取横向遍历,减少计算量
insertNode实现:根据要插入节点的parentId,找到父节点,然后把要插入的节点加入到父节点数组中
generateRoot:每次向listTree树加入节点后,在目标数组中删除该元素,直到目标数组为空
代码如下:
class listTree{
constructor(arr){
this.root = new Node(arr.find(item => item.parentId === 0))
this.generateRoot(arr)
}
generateRoot(arr){
let arrRest = arr;
let self = this;
let rootIndex = arr.findIndex(item => item.parentId === 0)
arrRest.splice(rootIndex,1)
reduceArrRest()
function reduceArrRest(){
arrRest.forEach((node,index) => {
let result = self.insertNode(new Node(node),node.parentId)
if(result){
arrRest.splice(index,1)
}
})
// 有剩余的元素没有插入到树结构, 继续循环插入
if(arrRest.length > 0){
reduceArrRest()
}
}
}
getNodeById(id){
if(this.root && this.root.id === id){
return this.root
}
let targetNode = null;
compareNodeId(id,this.root.childNodes)
return targetNode;
function compareNodeId(id, NodeList){
// 在遍历下一个节点时,先判断是否已经找到targetNode
if(targetNode){
return targetNode
}
// 先遍历NodeList数组(采取的广度遍历)
for ( let node of NodeList){
if(node.id === id){
targetNode = node
break
}
}
// NodeList数组中没找到,再到NodeList每个node的child中查找
if(!targetNode){
for ( let node of NodeList){
if(node.childNodes.length>0){
compareNodeId(id,node.childNodes)
}
}
}
return targetNode
}
}
insertNode(node, id){
let targetNode = this.getNodeById(id)
if(targetNode){
targetNode.childNodes.push(node)
return true
} else {
return false
}
}
}
递归遍历树结构
class listTree{
constructor(arr){
this.root = new Node(arr.find(item => item.parentId === 0))
}
// ...
toArray(){
let list = [];
pushNode(this.root)
function pushNode(node){
let { id, parentId, name } = node;
list.push({id, parentId, name})
if(node.childNodes.length>0){
for ( let nodeItem of node.childNodes){
pushNode(nodeItem)
}
}
}
return list
}
}
以上就实现了基本的功能
function listToTree(arr){
let ListTree = new listTree(arr)
console.log(JSON.stringify(ListTree.root,null, 2))
console.log(JSON.stringify(ListTree.toArray(),null,2))
}
listToTree(list)
树结构:
{
"id": 1001,
"parentId": 0,
"name": "AA",
"childNodes": [
{
"id": 1002,
"parentId": 1001,
"name": "BB",
"childNodes": [
{
"id": 1007,
"parentId": 1002,
"name": "GG",
"childNodes": []
},
{
"id": 1006,
"parentId": 1002,
"name": "FF",
"childNodes": []
}
]
},
{
"id": 1003,
"parentId": 1001,
"name": "CC",
"childNodes": [
{
"id": 1005,
"parentId": 1003,
"name": "EE",
"childNodes": [
{
"id": 1009,
"parentId": 1005,
"name": "II",
"childNodes": []
}
]
},
{
"id": 1004,
"parentId": 1003,
"name": "DD",
"childNodes": [
{
"id": 1008,
"parentId": 1004,
"name": "HH",
"childNodes": []
}
]
}
]
}
]
}
数组:
[
{
"id": 1001,
"parentId": 0,
"name": "AA"
},
{
"id": 1002,
"parentId": 1001,
"name": "BB"
},
{
"id": 1007,
"parentId": 1002,
"name": "GG"
},
{
"id": 1006,
"parentId": 1002,
"name": "FF"
},
{
"id": 1003,
"parentId": 1001,
"name": "CC"
},
{
"id": 1005,
"parentId": 1003,
"name": "EE"
},
{
"id": 1009,
"parentId": 1005,
"name": "II"
},
{
"id": 1004,
"parentId": 1003,
"name": "DD"
},
{
"id": 1008,
"parentId": 1004,
"name": "HH"
}
]
总结:树结构的形式有很多,不过还是会归结到树节点,树方法上。
文章浏览阅读1.5w次,点赞9次,收藏26次。简介一个创建某个文件到桌面快捷方式的BAT批处理.代码@echooff::设置程序或文件的完整路径(必选)setProgram=D:\Program Files (x86)\格式工厂.4.2.0\FormatFactory.exe::设置快捷方式名称(必选)setLnkName=格式工厂v4.2.0::设置程序的工作路径,一般为程序主目录,此项若留空,脚本将..._批处理创建桌面快捷方式
文章浏览阅读2k次。射频识别技术漫谈(6-10),概述RFID的通讯协议;射频ID卡的原理与实现,数据的传输与解码;介绍动物标签属性与数据传输;RFID识别号的变化等_芯片 ttf模式
文章浏览阅读1.1k次。今天小编心血来潮,为大家带来一个很有趣的项目,那就是使用 Python web 框架 Django 来实现支付宝支付,废话不多说,一起来看看如何实现吧。_django 对接支付宝接口流程
文章浏览阅读842次。Zabbix 5.0 LTS,跑了一年多了一直很稳定,前两天空间显示快满了,于是手贱清理了一下history_uint表(使用mysql truncate),结果折腾了一周。大概故障如下:然后zabbix论坛、各种群问了好久都没解决,最后自己一番折腾似乎搞定了。初步怀疑,应该是由于历史数据被清空后,zabbix需要去处理数据,但是数据量太大,跑不过来,所以来不及更新了(?)..._zabbix问题没有更新
文章浏览阅读296次。一、数据结构之字典 key-value
文章浏览阅读9.7k次,点赞3次,收藏13次。最近项目中遇到一个问题,是关于mybatis-plus的字段注解策略,记录一下。1问题调用了A组件(基础组件),来更新自身组件的数据,发现自己组件有个字段总是被清空。2原因分析调用的A组件的字段,属于基础字段,自己业务组件,对这个基础字段做了扩展,增加了业务字段。但是在自己的组件中的实体注解上,有一个注解使用错误。mybatis-plus封装的updateById方法,如果..._mybatisplus strategy
文章浏览阅读3.8k次。如何构建倒排索引,我们将这个过程叫做“索引构建”。如果我们的文档很多,这样索引就一次性装不下内存,该如何构建。硬件的限制 我们知道ram读写是随机的操作,只要输入相应的地址单元就能瞬间将数据读出来或者写进去。但是磁盘不行,磁盘必须有一个寻道的过程,外加一个旋转时间。那么只有涉及到磁盘,我们就可以考虑怎么节省I/O操作时间。【注】操作系统往往以数据块为单位进行读写。因为读一_为某一文档及集构件词项索引时,可使用哪些索引构建方法
文章浏览阅读836次。英特尔技术与制造事业部副总裁卞成刚7日在财富论坛间隙接受中新社记者采访时表示,该公司看好中国市场前景,扎根中国并以此走向世界是目前最重要的战略之一。卞成刚说,目前该公司正面临战略转型,即从传统PC服务领域扩展至所有智能设施领域,特别是移动终端。而中国目前正引领全球手机市场,预计未来手机、平板电脑等方面的发明创新将大量在中国市场涌现,并推向全球。持相同态度的还有英特尔中国区执行董事戈峻。戈峻
文章浏览阅读627次。https://blog.csdn.net/zrs19800702/article/details/53101213http://blog.csdn.net/lzw06061139/article/details/51445311https://my.oschina.net/linuxhunter/blog/654080rgw 概述Ceph 通过radosgw提供RES..._radosgw -c
文章浏览阅读3.7k次,点赞6次,收藏9次。我为什么选择ECharts ? 本周学校课程设计,原本随机佛系选了一个51单片机来做音乐播放器,结果在粗略玩了CN-DBpedia两天后才回过神,课设还没有开始整。于是懒癌发作,碍于身上还有比赛的作品没交,本菜鸡对硬件也没啥天赋,所以就直接把题目切换成软件方面的题目。写python的同学选择了一个时间序列数据的可视化曲线程序设计题目,果真python在数据可视化这一点性能很优秀。..._echarts 时间序列
文章浏览阅读1.6k次。事件类:/** * * * @className: EarlyWarnPublishEvent * * @description:数据风险预警发布事件 * * @param: * * @return: * * @throws: * * @author: lizz * * @date: 2020/05/06 15:31 * */public cl..._applicationeventpublisheraware
文章浏览阅读1.2k次。如需转载请注明出处!点击小图片转到图片查看的页面在Android开发中很常用到,抱着学习和分享的心态,在这里写下自己自定义的一个ImageView,可以实现类似微信朋友圈中查看图片的功能和效果。主要功能需求:1.缩放限制:自由缩放,有最大和最小的缩放限制 2居中显示:.若图片没充满整个ImageView,则缩放过程将图片居中 3.双击缩放:根据当前缩放的状态,双击放大两倍或缩小到原来 4.单指_imageview图片边界回弹