[ Graph ]
3. class 키워드로 Graph 구현
class GraphWithAdjacencyMatrix {
constructor() {
this.matrix = [];
}
addVertex() {
const currentLength = this.matrix.length;
for (let i = 0; i < currentLength; i++) {
this.matrix[i].push(0);
}
this.matrix.push(new Array(currentLength + 1).fill(0));
}
contains(vertex) {
if(vertex < this.matrix.length){
return true
}
return false
}
addEdge(from, to) {
const currentLength = this.matrix.length - 1;
if (from === undefined || to === undefined) {
console.log("2개의 인자가 있어야 합니다.");
return;
}
if (
from > currentLength ||
to > currentLength ||
from < 0 ||
to < 0
) {
console.log("범위가 매트릭스 밖에 있습니다.");
return;
}
this.matrix[from][to] = 1;
}
hasEdge(from, to) {
if(this.matrix[from][to] === 1){
return true
}
return false
}
removeEdge(from, to) {
const currentLength = this.matrix.length - 1;
if (from === undefined || to === undefined) {
console.log("2개의 인자가 있어야 합니다.");
return;
}
if (
from > currentLength ||
to > currentLength ||
from < 0 ||
to < 0
) {
console.log("범위가 매트릭스 밖에 있습니다.");
return;
}
this.matrix[from][to] = 0;
}
}
[ Tree ]
3. class 키워드로 Tree 구현
class Tree {
constructor(value) {
this.value = value;
this.children = [];
}
insertNode(value) {
const childNode = new Tree(value);
this.children.push(childNode);
}
contains(value) {
if (this.value === value) {
return true;
}
for (let i = 0; i < this.children.length; i += 1) {
const childNode = this.children[i];
if (childNode.contains(value)) {
return true;
}
}
return false;
}
}
[ BST ]
3. class 키워드로 BST 구현
class BinarySearchTree {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
insert(value) {
if (value < this.value) {
if (this.left === null) {
this.left = new BinarySearchTree(value);
}
else {
this.left.insert(value);
}
}
else if (value > this.value) {
if (this.right === null) {
this.right = new BinarySearchTree(value);
}
else {
this.right.insert(value);
}
} else {
}
}
contains(value) {
if (value === this.value) {
return true;
}
if (value < this.value) {
return !!(this.left && this.left.contains(value));
}
if (value > this.value) {
return !!(this.right && this.right.contains(value));
}
}
preorder(callback) {
callback(this.value);
if (this.left) {
this.left.preorder(callback);
}
if (this.right) {
this.right.preorder(callback);
}
}
inorder(callback) {
if (this.left) {
this.left.inorder(callback);
}
callback(this.value);
if (this.right) {
this.right.inorder(callback);
}
}
postorder(callback) {
if (this.left) {
this.left.postorder(callback);
}
if (this.right) {
this.right.postorder(callback);
}
callback(this.value);
}
}