Javascript 从边对和根构建树
我正试图编写一个程序,将一组边对转换成一棵树。我有根。在本例中,根为2 唯一的限制是,每个节点最多可以有2个子节点 样本输入:Javascript 从边对和根构建树,javascript,algorithm,tree,Javascript,Algorithm,Tree,我正试图编写一个程序,将一组边对转换成一棵树。我有根。在本例中,根为2 唯一的限制是,每个节点最多可以有2个子节点 样本输入: [[1,2],[2,3],[3,4],[1,5]] 预期产出: { "id":2, "children":[ { "id":1, "children":[ { "id":5 } ] }, {
[[1,2],[2,3],[3,4],[1,5]]
预期产出:
{
"id":2,
"children":[
{
"id":1,
"children":[
{
"id":5
}
]
},
{
"id":3,
"children":[
{
"id":4
}
]
}
]
}
enter code here
看起来像这样:
2
/ \
1 3
/ \
5 4
这是我迄今为止的尝试:
const tree = {};
const edgePairs = [[1, 2], [2, 3], [3, 4], [1, 5]];
let root = 2;
let children;
function hasTwoChildren(node) {
let counter = 0;
for (const i in edgePairs) {
if (edgePairs[i].includes(node)) counter++;
}
return counter === 2;
}
function getChildren(root) {
const children = [];
for (let i = 0; i < edgePairs.length; i++) {
if (edgePairs[i][0] === root) children.push(edgePairs[i][1]);
if (edgePairs[i][1] === root) children.push(edgePairs[i][0]);
}
return children;
}
function makeTree(tree, root) {
if (tree.id === undefined) {
tree.id = root;
} else if (hasTwoChildren(root)) {
children = getChildren(root);
tree.children = makeTree(tree, children[0]);
makeTree(tree, children[1]);
} else {
makeTree(tree, children[0]);
}
return tree;
}
for (const i in edgePairs) {
makeTree(tree, root);
}
consttree={};
常量edgePairs=[[1,2]、[2,3]、[3,4]、[1,5];
设根=2;
让孩子们;
函数hasTwoChildren(节点){
设计数器=0;
用于(边墙中的常数i){
if(edgePairs[i].包括(节点))计数器++;
}
返回计数器===2;
}
函数getChildren(根){
const children=[];
for(设i=0;i
感觉这应该很简单,但我遗漏了一些东西。。有什么帮助吗?:) 哇,我喜欢这个问题。而且也很有挑战性! 这是我第一次对某个问题采取递归方法。我想我终于找到了答案
设root=2;
//更复杂的数据(1个分支不连接到任何其他节点)
设节点=[[1,2],[2,3],[3,4],[1,5],[1,6],[2,8],[100101];
函数createTree(根,节点){
让孩子们=[];
for(设i=0;i log(createTree(根,节点))
makeTree
不应将树
作为其参数。它应该创建树对象本身。给它边对和它应该构造的节点的id,并让它返回一个完成的树节点。