JS 两树交集
Posted 码小余の博客
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS 两树交集相关的知识,希望对你有一定的参考价值。
求两个树形结构的交集
思路是遍历递归第一棵树,在遍历内部再次遍历递归第二棵树,添加层级,用层级和id进行比较,如果相等就添加不用删除的标记
然后在下面在遍历递归tree2,删除没有exist的节点,完成
const tree1 = [
id: 1,
name: 'aaa',
,
id: 2,
name: 'bbb',
children: [
id: 3,
name: 'ccc'
,
id: 4,
name: 'ddd'
]
,
id: 5,
name: 'eee',
children: [
id: 6,
name: 'fff'
,
id: 7,
name: 'ggg',
children: [
id: 8,
name: 'hhh',
,
id: 9,
name: 'iii',
]
]
,
]
const tree2 = [
id: 1,
name: 'aaa',
,
id: 2,
name: 'bbb',
children: [
id: 3,
name: 'ccc'
,
id: 44,
name: 'jjj'
]
,
id: 5,
name: 'eee',
children: [
id: 6,
name: 'fff'
,
id: 7,
name: 'ggg',
children: [
id: 100,
name: 'zzz'
,
id: 8,
name: 'hhh',
,
id: 99,
name: 'kkk',
]
]
,
]
/**
* 递归遍历树节点
* @param * nodes 树节点数据
*/
function f (nodes = [], nodes2 = [], level = 0, level2 = 0)
level++
nodes.forEach((node) =>
node.level = level
// console.log(node);
// 循环遍历tree2
function f2 (nodes2 = [], level2 = 0)
// console.log("nodes2: ", nodes2);
level2++
nodes2.forEach((node2) =>
node2.level = level2
// console.log(node2);
if (node.level === node2.level && node.id === node2.id)
node2.exist = true
var mapNode2 = new Map()
for (var k2 in node2)
mapNode2.set(k2, node2[k2])
if (mapNode2.has("children")) f2(mapNode2.get("children"), level2)
)
f2(nodes2)
var mapNode = new Map()
for (var k in node)
mapNode.set(k, node[k])
if (mapNode.has("children")) f(mapNode.get("children"), nodes2, level)
)
f(tree1, tree2)
function filterFn (nodes = [])
for (let i = nodes.length - 1; i >= 0; i--)
var mapNode = new Map()
for (var k in nodes[i])
mapNode.set(k, nodes[i][k])
if (!mapNode.has("exist"))
nodes.splice(i, 1)
if (mapNode.has("children")) filterFn(mapNode.get("children"))
filterFn(tree2)
// 两树交集如下结果
console.log(tree2);
emm,不会写,就写成这样了,有大佬会写的帮忙看看有没有其他的写法~
以上是关于JS 两树交集的主要内容,如果未能解决你的问题,请参考以下文章