function Node(id, v, pid) {
this.id = id;
this.v = v;
this.pid = pid;
}
let nodes = [
new Node(0, 0, null),
new Node(4, 4, 1),
new Node(1, 1, 0),
new Node(5, 5, 1),
new Node(2, 2, 0),
new Node(8, 8, 2),
new Node(9, 9, 2),
new Node(19, 19, 2),
];
function buildTree(nodes, rootID) {
let root = nodes.find(node => {
return node.id === rootID
});
if(!root) return null;
function appendChildToNode(node) {
let children = [];
nodes.forEach(n => {
if (n.pid === node.id) {
children.push(n)
appendChildToNode(n)
}
});
node.children = children ;
}
appendChildToNode(root, rootID);
return root;
}
let res = buildTree(nodes, 0);
// 深度优先遍历
function dfs(t) {
if (Array.isArray(t)) {
t.forEach(n => {
dfs(n)
})
} else {
console.log(t)
dfs(t.children)
}
}
dfs(res)
// 广度优先遍历
function bfs(t) {
let r = [t];
while (r && r.length) {
let f = r.shift()
console.log(f)
if (f.children) {
r = r.concat(f.children)
}
}
}
bfs(res)
通过id和父id重建树
最新推荐文章于 2022-12-08 14:19:52 发布