Created
July 3, 2019 23:21
-
-
Save wisniewski94/c2b113c24ff02321dd392c497db995d6 to your computer and use it in GitHub Desktop.
N-ary Tree Generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node { | |
constructor(parent, id) { | |
this.id = id; | |
this.child = []; | |
this.parent = parent; | |
} | |
setChild(child) { | |
this.child.push(child); | |
} | |
} | |
let tree = []; | |
const generateTree = (nodes, levels, _cLevel, _id, _cNode) => { | |
if (_cLevel >= levels) return; | |
if (_cLevel == null) (_cLevel = 0), (_id = 1); | |
let _tNode; | |
var _created = []; | |
if (_cLevel == 0) { | |
_cNode = new Node(null, _id); | |
tree.push(_cNode); | |
_created.push(_cNode); | |
_tNode = _cNode; | |
} else { | |
const children = Math.floor(Math.random() * (nodes - 0)) + 0; | |
let i = 0; | |
while (i <= children) { | |
_id++; | |
_tNode = new Node(_cNode.id, _id); | |
_cNode.setChild(_tNode.id); | |
tree.push(_tNode); | |
_created.push(_tNode); | |
i++; | |
} | |
} | |
_cLevel++; | |
_created.forEach(element => { | |
generateTree(nodes, levels, _cLevel, tree.length, element); | |
}); | |
}; | |
generateTree(3, 4); | |
console.log(tree); |
@lightningblade1 I don't even remember why I created this code in the first place 😂 I think I was working on some tree search algo and needed a random tree.
So you need to know only 2 -> nodes and levels
levels is the depth of tree e.g. if levels is 2 then all nodes will have only 1 parent. So it's parent (1 level) + 1 level of children.
If level is 1, then there will be only 1 node.
nodes is max nodes per level which is decreased by Math.random() on line 26
Not the cleanest code but fun to call
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
could you please tell the purpose of all the parameters?