- 마지막 레벨을 제외한 모든 노드가 가득 차있어야한다. - 마지막 레벨의 노드는 전부 차 있지 않아도 되지만 왼쪽이 채워져 잇어야 한다.
Binary Search Tree의 시간 복잡도 (Big-O)
데이터 삽입 : n개의 데이터가 있을 때, 한 번 탐색을 할 때마다 1/2씩 탐색 범위를 줄여준다. 아래와 같이 계산을 하면 O(logN)의 복잡도가 나온다. (log는 밑이 2이다)
최악의 경우 O(n)이 될 수 있다. Binary Search Tree ADT의 정의
BinarySearchTree : Object로 정의된 이진트리 그 자체
left :노드보다 더 작은 값을 갖는 자식 노드
right: 노드보다 저 큰 값을 갖는 자식 노드
Binary Search를 대표하는 연산
insertNode(value) : Node를 삽입
contains(value) : Node 탐색
delete(value) : Node 삭제
ADT를 기반으로 구현을 해보자.
Binary Search Tree의 구현
Class를 이용한 BST 구현
// Binary Tree ADT
// Tree : 객체로 정의된 Tree 그 자체
// left : Node의 자식 중 왼쪽 node
// Right : Node의 자식 중 오른쪽 node
// Tree를 대표하는 연산
// insertNode(value) : Node에 데이터를 저장
// search(val) : 값을 찾는다.
/* Pesudocode ---------------------------------------*/
//------------ insert(value)-------------------------//
// insertNnode(val)
// if -> this.val >val
// if -> this.left true -> this.left.insertNode(vel)
// else -> new Tree(val)
// else if -> this.val<val
// if -> this.right true-> this.right.insertNode(val)
// else -> new.Tree(val)
//------------ search(val)-------------------------//
// if this.value===value -> return true
// if this.value>value -> return this.left.search(value)
// else return this.right.search(value)
class BinaryTree {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
insertNode(value) {
if (this.value > value) {
this.left
? this.left.insertNode(value)
: (this.left = new BinaryTree(value));
} else if (this.value < value)
this.right
? this.right.insertNode(value)
: (this.right = new BinaryTree(value));
return " 이미 존재하는 값";
}
contains(value) {
if (this.value === value) return true;
if (this.value > value) {
if (this.left)
return this.left.value === value ?? this.left.contains(value);
} else {
if (this.right)
return this.right.value === value ?? this.right.contains(value);
}
}
}
// 삭제 구현은 아직 하지 않음