Tree는 노드로 구성된 계층적 자료구조로 그래프의 한 종류입니다.
Tree는 그래프와 같이 노드(vertex)와 간선(edge)들로 이루어져 있습니다. 그중에 방향성이 존재하는 directed graph이지만 Tree는 Cycle이 존재하지 않는 비순환 그래프의 한 종류입니다.
즉, 방향성이 있는 비순환 그래프입니다.
- insertNode : 트리에 노드를 추가합니다.
- contains : 트리에 해당 노드가 존재하는지 여부를 반환합니다.
class TreeNode {
constructor(value) {
this.value = value;
this.children = [];
}
insertNode(value) {
const tree = new TreeNode(value);// 새로운 TreeNode를 생성
this.children.push(tree); // 생성한 TreeNode를 자식 노드에 push
}
contains(value) {
let bool = false;
if (this.value === value) {//입력받은 value가 존재하면 true를 return
bool = true;
} else {
for (const item of this.children) {
if (item.contains(value)) { // 재귀를 통해 자식노드에 value가 존재하면 true를 return
bool = true;
}
}
}
return bool;
}
}
module.exports = TreeNode;