이진 검색 트리
3259 단어 hacktoberfestjavascript
/*
Example For Binary Search Tree
__10__
/ \
5 13
/ \ / \
2 7 11 16
/\ \ \
1 3 9 18
*/
class Node {
constructor(value){
this.value = value;
this.left = null;
this.right = null;
}
}
class BinarySearchTree {
constructor(){
this.root = null;
}
// Insert a New value in tree
insert(value) {
var newNode = new Node(value);
if(this.root === null) {
this.root = newNode;
return this;
} else {
var current = this.root;
while(true) {
if(value < current.value) {
if(current.left === null) {
current.left = newNode;
console.log(` -> ${current.value} left value -> ${value} added `)
return this;
} else {
current = current.left;
}
} else if(value > current.value) {
if (current.right === null) {
current.right = newNode;
console.log(` -> ${current.value} right value -> ${value} added `)
return this;
} else {
current = current.right;
}
}
if(current.value == value) {
console.log(` -> ${value} is Duplicate value Please Enter Unique Value `)
return;
}
}
}
}
// find The Value in tree
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 {
console.log(`Founded Successfully -> ${value}`);
return current;
}
}
if(!found) console.log(`Not Founded -> ${value}`);
return current;
}
// Same as on find
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 {
console.log(`Founded Successfully -> ${value}`);
return current;
}
}
if(!found) console.log(`Not Founded -> ${value}`);
return current;
}
}
var tree = new BinarySearchTree();
tree.insert(10)
tree.insert(5)
tree.insert(13)
tree.insert(2)
tree.insert(7)
tree.insert(11)
tree.insert(16)
Reference
이 문제에 관하여(이진 검색 트리), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/aashish578/binary-search-trees-47a2텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)