本文主要是介绍提高树结构访问效率,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
问题
树节点嵌套非常深的时候,想要直接访问某个节点非常困难
需求
- 修改和查找数据时候不需要 obj.xx.xx.xx.xx这么多层
- 可以从子节点往上找他的索引父节点
思路
新增辅助数据,用数组替代树结构访问,不修改原来的树结构,这样就可以利用数组的索引来查询了
针对场景
- 知道节点2索引,找父节点索引
- 知道父节点的索引,找父节点数据
- 知道一个节点的索引,不断的找到它的父节点
- 知道父索引,遍历找到子索引的所以子节点
代码
树结构
var obj = [{name: "1",index: "0", //辅助调试,真实数据不需要children: [{name: "1-1",index: "1",children: [{name: "1-1-1",index: 2,},{name: "1-1-2",index: 3,},],},{name: "1-2",index: 4,children: [{name: "1-2-1",index: 5,},{name: "1-2-2",index: 6,},],},],},];
新增辅助数据
//前遍历,存储obj的元素,把obj树节点扁平化const nodelist = [];//从左到右,子节点的索引,数组的索引就是nodelist里面的索引let childrenIndex = [];//从左到右,按照排序,记录对应索引的父节点,数组的索引就是nodelist里面的索引let parentIndex = [];//二维数组 [[],null],存储有子节点的节点的索引,没有的话null,不管层级多深都是二维数组,一维数组的索引就是nodelist里面的索引let indexTree = [];
全部代码
var obj = [{name: "1",index: "0", //辅助调试,真实数据不需要children: [{name: "1-1",index: "1",children: [{name: "1-1-1",index: 2,},{name: "1-1-2",index: 3,},],},{name: "1-2",index: 4,children: [{name: "1-2-1",index: 5,},{name: "1-2-2",index: 6,},],},],},];//前遍历,存储obj的元素,把obj树节点扁平化const nodelist = [];//从右边到左边,子节点的索引let childrenIndex = [];//从左到右,按照排序,记录对应索引的父节点let parentIndex = [];//二维数组 [[],null],存储有子节点的节点的索引,没有的话nulllet indexTree = [];// parentIndex.push({ pindex: -1, obj: obj })let index = -1;function childrenIdx(obj, pIndex, childrenArr) {for (let i = 0; i < obj.length; i++) {let item = obj[i];index++;let currentIndex = childrenIndex.length;childrenIndex.push({ index: index, currobj: obj[i] });parentIndex.push({ pindex: pIndex, currobj: obj[i] });nodelist.push(item);childrenArr.push(index);if (obj[i].children) {let arr = [];indexTree.push(arr);childrenIdx(obj[i].children, currentIndex, arr);//console.log("index", index, 'item.index', item.index, "i", i)} else {indexTree.push(null);}}}//第一个节点的pindex等于-1childrenIdx(obj, -1, []);console.log("childrenIdxid", childrenIndex, "parentIndex", parentIndex);console.log("nodelist", nodelist);console.log("indexTree,", indexTree);//场景1,知道节点2索引,找父节点索引function getparentIndex(childrenIdx) {return parentIndex[childrenIdx];}//场景2,知道父节点的索引,找父节点数据function getNodeByIndex(index) {return nodelist[index];}let pindexInfo = getparentIndex(2);console.log("2序号节点的父节点",pindexInfo,"父节点数据",getNodeByIndex(pindexInfo.pindex));//场景2,知道一个节点的索引,不断的找到它的父节点let currIndex = 2;function nodeParentList() {let currParentList = [];while (currIndex != -1) {let pindexInfo = getparentIndex(currIndex);let pNode = getNodeByIndex(pindexInfo.pindex);currParentList.push(pNode);currIndex = pindexInfo.pindex;}return currParentList;}console.log("索引为2的node的父节点集合", nodeParentList(2));//场景3,知道父索引,遍历找到子索引的所以子节点let parentIdex = 4; //父节点的索引function getChildrens(index) {let childenIndexs = indexTree[index];console.log("childenIndexs", childenIndexs);if (childenIndexs) {return childenIndexs.map((item) => {return nodelist[item];});}}console.log("父节点下的所有子节点:", getChildrens(parentIdex));</script>
这篇关于提高树结构访问效率的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!