赞
踩
在线示例https://codesandbox.io/embed/myp00yr1xx?fontsize=14/react-tree2
[ { id: 5, name: "节点0-3-5", pid: 3 }, { id: 4, name: "节点0-3-4", pid: 3 }, { id: 0, name: "根节点", pid: -1 }, { id: 6, name: "节点0-1-6", pid: 1 }, { id: 2, name: "节点0-2", pid: 0 }, { id: 3, name: "节点0-3", pid: 0 }, { id: 1, name: "节点0-1", pid: 0 } ]
{ id: 0, name: "根节点", pid: -1, children: [ { id: 1, name: "节点0-1", pid: 0, children: [ { id: 6, name: "节点0-1-6", pid: 1 } ] }, { id: 2, name: "节点0-2", pid: 0 }, { id: 3, name: "节点0-3", pid: 0, children: [ { id: 4, name: "节点0-3-4", pid: 3 }, { id: 5, name: "节点0-3-5", pid: 3 } ] } ] }
在数据结构中,我们分析图结构的节点之间的关系时,经常提到关系矩阵。我们可以用二维数组定义一个这样的关系矩阵。
// 假设原始节点数据是数组 const createShipMatrix = (origin) => { if (!origin || !origin.length) return; const shipMatrix = []; // 初始化 const len = origin.length; for (let i = 0; i<len; i++ ){ shipMatrix[i]=[]; } // 假设有两个节点origin[a]与origin[b],我们令 // shipMatrix[a][b] = 1,表示orgin[a]是origin[b]的父节点; // shipMatrix[a][b] = -1,表示orgin[a]是origin[b]的子节点; // shipMatrix[a][b] = 0,表示orgin[a]和origin[b]没有直接关系。 for (let i = 0; i<len; i++) { for (let j = 0; j<len; j++) { if (i==j){
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。