Created
January 9, 2021 13:55
-
-
Save samilkahraman/6fdf9071f788a75ff09bfe5e60b51281 to your computer and use it in GitHub Desktop.
Nodejs Tree Yapısı
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
function Node(data) { | |
this.id = data.id; | |
this.name = data.name; | |
this.children = []; | |
} | |
class Tree { | |
constructor() { | |
this.root = null; | |
} | |
add(data, toNodeData) { | |
const node = new Node(data); | |
// If the toNodeData arg is passed, find it. Otherwise, store null. | |
const parent = toNodeData ? this.findBFS(toNodeData) : null; | |
// Push new node to parent whose value matches toNodeData | |
if (parent) { | |
parent.children.push(node); | |
} else { | |
// If there's no parent, make this the root node | |
if (!this.root) this.root = node; | |
else return 'Tried to store node as root when root already exists.'; | |
} | |
} | |
findBFS(data) { | |
const queue = [this.root]; | |
let _node = null; | |
// Go thru every node in BFS | |
this.traverseBFS((node) => { | |
// Return match if found | |
if (node.id === data) { | |
_node = node; | |
} | |
}); | |
return _node; | |
} | |
traverseBFS(cb) { | |
const queue = [this.root]; | |
if (cb) | |
while (queue.length) { | |
// Store current node & remove it from queue | |
const node = queue.shift(); | |
cb(node); | |
// Push children of current node to end of queue | |
for (const child of node.children) { | |
queue.push(child); | |
} | |
} | |
} | |
} | |
module.exports = Tree; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment