Muscardinus
Binary Search Tree 구현 본문
728x90
이진탐색트리 시뮬레이션 연습 사이트
class Node {
constructor(value){
this.left = null;
this.right = null;
this.value = value;
}
}
class BinarySearchTree {
constructor(){
this.root = null;
}
insert(value){
const newNode = new Node(value);
if (!this.root) this.root = newNode;
else {
let currentNode = this.root;
while(1) {
if (value < currentNode.value) {
if (!currentNode.left) {
currentNode.left = newNode;
return this;
}
currentNode = currentNode.left;
} else {
if (!currentNode.right) {
currentNode.right = newNode;
return this;
}
currentNode = currentNode.right;
}
}
}
}
lookup(value){
if (!this.root) return false;
let currentNode = this.root;
while(currentNode) {
if (value < currentNode.value) currentNode = currentNode.left;
else if (value > currentNode.value) currentNode = currentNode.right;
else if (value === currentNode.value) return currentNode;
}
return false;
}
remove(value) {
if (!this.root) return false;
let currentNode = this.root;
let parentNode = null;
while(currentNode) {
if (value < currentNode.value) {
parentNode = currentNode;
currentNode = currentNode.left;
} else if (value > currentNode.value) {
parentNode = currentNode;
currentNode = currentNode.right;
} else if (currentNode.value === value) {
if (!currentNode.right) {
if (!parentNode) this.root = currentNode.left;
else {
if (currentNode.value < parentNode.value) parentNode.left = currentNode.left;
else if (currentNode.value > parentNode.value) parentNode.right = currentNode.left;
}
} else if (!currentNode.right.left) {
if (!parentNode) this.root = currentNode.left;
else {
currentNode.right.left = currentNode.left;
if (currentNode.value < parentNode.value) parentNode.left = currentNode.right;
else if (currentNode.value > parentNode.value) parentNode.right = currentNode.right;
}
} else {
let leftmost = currentNode.right.left;
let leftmostParent = currentNode.right;
while (leftmost.left) {
leftmostParent = leftmost;
leftmost = leftmost.left;
}
leftmostParent.left = leftmost.right;
leftmost.left = currentNode.left;
leftmost.right = currentNode.right;
if (!parentNode) this.root = leftmost;
else {
if (currentNode.value < parentNode.value) parentNode.left = leftmost;
else if (currentNode.value > parentNode.value) parentNode.right = leftmost;
}
}
return true;
}
}
}
}
728x90
'DataStructure' 카테고리의 다른 글
Undirected Graph 구현 (0) | 2020.12.13 |
---|---|
Queue 구현 (0) | 2020.12.12 |
Stack 구현 (0) | 2020.12.12 |
Double Linked List 구현 (0) | 2020.10.15 |
Linked List 구현 (0) | 2020.10.15 |
Comments