I'm creating a website to interact with courses and their prerequisites.
This is for free, isn't a homework and I'm using this project to learn MERN
I did this tree schema which represents all courses and their dependencies.
Notice that a course can have more than one prerequisite.
So I'm having rough time translating this into TDA. I have been trying with multi parents tree but I have no results due to:
- Can't recreate multiparents into one node
- Can't traverse a tree with implementations so I can't know which courses are available
I was using this Tree/Node definition in JS. I didn't try with Python but I have no problem in using another language even when I know language isn't the problem.
class Tree {
constructor(root) {
this._root = root || null;
}
_traverse(callback) {
const self = this;
function goThrough(node) {
callback(node);
node.children.forEach((child) => {
goThrough(child);
});
}
goThrough(this._root);
}
_addNode(value, parentValue) {
const newNode = {
value,
children: []
};
if (this._root === null) {
this._root = newNode;
return;
}
this._traverse((node) => {
if (node.value === parentValue) {
node.children.push(newNode);
}
});
}
_removeNode(value) {
this._traverse((node) => {
node.children.forEach((childNode, index) => {
if (childNode.value === value) {
node.children.splice(index, 1);
}
});
})
}
_search(value) {
let returnNode = 'Not Found';
this._traverse((node) => {
if (node.value === value) {
returnNode = node;
}
});
return returnNode;
}
_displayLeafs(parentValue) {
const parentNode = typeof parentValue === 'string' ? this._search(parentValue) : parentValue ;
let leafsRet = [];
if (parentValue.children && !parentValue.children.length) {
return parentValue;
}
parentNode.children.forEach((child) => {
leafsRet.push(this._displayLeafs(child));
});
return leafsRet.flat();
}
}
class Node {
constructor(value, children) {
this.value = value;
this.children = children;
}
}
const malla = new Tree();
malla._addNode('root');
malla._addNode('CMB1000','root');
malla._addNode('CMB1001','root');
malla._addNode('CIT1000','root');
malla._addNode('FIC1000','root');
malla._addNode('CBQ100','root');
malla._addNode('CIT1010','CIT1000');
console.log(malla._displayLeafs('root'));
I didn't follow inserting new nodes because I'm not getting results as expected.
Can anyone give a hint about a tree implemention that may I know? Or maybe a better approach to this situation?
Thanks for your time!