반응형
SMALL
class Node {
constructor(data) {
this.data = data;
this.children = [];
}
add(data) {
this.children.push(new Node(data));
}
remove(data) {
this.children = this.children.filter((child) =>
child.data === data ? false : true
);
}
}
class Tree {
constructor() {
this.root = null;
}
BFS(fn) {
if (this.root === null) return;
const unvisitedQueue = [this.root];
while (unvisitedQueue.length !== 0) {
const current = unvisitedQueue.shift();
unvisitedQueue.push(...current.children);
fn(current);
}
}
DFS(fn) {
if (this.root === null) return null;
const unvisitedList = [this.root];
while (unvisitedList.length !== 0) {
const current = unvisitedList.shift();
unvisitedList.unshift(...current.children);
fn(current);
}
}
}
// ------------------------------------
const t = new Tree();
t.root = new Node("a");
t.root.add("b");
t.root.children[0].add("c");
t.root.add("d");
const BFSArray = [];
const DFSArray = [];
t.BFS((node) => BFSArray.push(node.data));
t.DFS((node) => DFSArray.push(node.data));
console.log("BFS: ", BFSArray);
console.log("DFS: ", DFSArray);
console.log("TREE: ", t.root);
반응형
LIST
'Coding Interview' 카테고리의 다른 글
[LeetCode] BFS-DFS 207. Course Schedule (feat. 위상정렬(Topological Sort)) (1) | 2022.09.25 |
---|---|
[LeetCode] DFS-BFS 329. Longest Increasing Path in a Matrix (1) | 2022.09.25 |
[LeetCode] DFS-BFS 314. Binary Tree Vertical Order Traversal (0) | 2022.09.24 |
[LeetCode] BFS-DFS 236. Lowest Common Ancestor of a Binary Tree (2) | 2022.09.24 |
[LeetCode] BFS-DFS 200. Number of Islands (0) | 2022.09.24 |