
노드들이 부모/자식 관계로 이루어진 자료구조.
앞에서 배운 리스트들은 선형구조(linear) 이지만, 트리는 비선형구조(nonlinear)이다.
HTML DOM
Network Routing
Abstract syntax tree
AI
Folders in Operating system
Computer file system
아래의 것들 이외에도 매우 다양한 종류의 트리가 존재한다.
Q. 유효한 BST인가?
정답 : 아니다. 8의 오른쪽 자식 노드가 8보다 커야 하는데 더 작기 때문이다.
정답 : 아니다. 자식 노드 수가 최대 2개여야 하는데 10의 자식 노드가 3개 이므로 이진 트리가 될 수 없다.
class Node {
constructor(value){
this.value = value;
this.left = null;
this.right = null;
}
}
class BinarySearchTree {
constructor(){
this.root = null;
}
}
// 10
// 7 15
// 9
var tree = new BinarySearchTree();
tree.root = new Node(10);
tree.root.right = new Node(15);
tree.root.left = new Node(7);
tree.root.left.right = new Node(9);
1. insert( )
적절한 위치에 값을 넣어주는 메소드.
순환식/재귀식 중 선택해서 풀면 된다.
class Node {
constructor(value){
this.value = value;
this.left = null;
this.right = null;
}
}
class BinarySearchTree {
constructor(){
this.root = null;
}
insert(value){
var newNode = new Node(value);
if(this.root === null){
this.root = newNode;
return this;
}
var current = this.root;
while(true){
if(value === current.value) return undefined;
if(value < current.value){
if(current.left === null){
current.left = newNode;
return this;
}
current = current.left;
} else {
if(current.right === null){
current.right = newNode;
return this;
}
current = current.right;
}
}
}
}
// 10
// 5 13
// 2 7 11 16
var tree = new BinarySearchTree();
tree.insert(10)
tree.insert(5)
tree.insert(13)
tree.insert(11)
tree.insert(2)
tree.insert(16)
tree.insert(7)
2. find( )
트리에 해당 값이 존재하는지 확인(해당 값 출력)
+contains( ) : 트리에 해당 값이 존재하는지 확인(T/F 출력)
class Node {
constructor(value){
this.value = value;
this.left = null;
this.right = null;
}
}
class BinarySearchTree {
constructor(){
this.root = null;
}
insert(value){
var newNode = new Node(value);
if(this.root === null){
this.root = newNode;
return this;
}
var current = this.root;
while(true){
if(value === current.value) return undefined;
if(value < current.value){
if(current.left === null){
current.left = newNode;
return this;
}
current = current.left;
} else {
if(current.right === null){
current.right = newNode;
return this;
}
current = current.right;
}
}
}
find(value){
if(this.root === null) return false;
var current = this.root,
found = false;
while(current && !found){
if(value < current.value){
current = current.left;
} else if(value > current.value){
current = current.right;
} else {
found = true;
}
}
if(!found) return undefined;
return current;
}
contains(value){
if(this.root === null) return false;
var current = this.root,
found = false;
while(current && !found){
if(value < current.value){
current = current.left;
} else if(value > current.value){
current = current.right;
} else {
return true;
}
}
return false;
}
}
평균적인 & 최고의 경우,
삽입 & 탐색 : O(log n)
최악의 경우 : 연결 리스트 형태로 되어있는 트리의 경우
해결책 : 트리를 안쓰면 된다.
