the others/Algorithm
Binary Search Tree ꡬν : pre-order / in-order / post-order
ciocio
2021. 9. 23. 23:42
π Binary Search Tree
class BinarySearchTree {
constructor(value){
this.value = value;
this.left = null;
this.right = null;
}
insert(value) {
if(value < this.value){
if(this.left === null){
this.left = new BinarySearchTree(value);
}
else{
this.left.insert(value);
}
}
else if(value > this.value){
if(this.right === null){
this.right = new BinarySearchTree(value);
}
else{
this.right.insert(value);
}
}
}
contains(value) {
if(value === this.value){
return true;
}
else if(this.left === null || this.right === null){
return false;
}
if(value < this.value){
return (this.left && this.left.contains(value));
}
if(value > this.value){
return (this.right && this.right.contains(value));
}
}
preorder(callback) {
callback(this.value);
if(this.left){
this.left.preorder(callback);
}
if(this.right){
this.right.preorder(callback);
}
}
inorder(callback) {
if(this.left){
this.left.inorder(callback);
}
callback(this.value);
if(this.right){
this.right.inorder(callback);
}
}
postorder(callback) {
if(this.left){
this.left.postorder(callback);
}
if(this.right){
this.right.postorder(callback);
}
callback(this.value);
}
}
let arr = [];
let callback = function (value) {
arr.push(value);
};
const rootNode = new BinarySearchTree(10);
rootNode.insert(8);
rootNode.insert(3);
rootNode.insert(7);
rootNode.insert(5);
rootNode.insert(15);
rootNode.insert(16);
rootNode.insert(11);
rootNode.insert(14);
rootNode.postorder(callback);
π Tree
π Tree Traversal : preorder
μΌμͺ½λΆν° κ²μ¬νλ, (λ£¨νΈ λ Έλμμ μμν΄μ) λ§λλ λ Έλ μ‘±μ‘± κ²μ¬ μν ν μ€λ₯Έμͺ½μΌλ‘ λμ΄κ°λ νν
π Tree Traversal : inorder
μ μΌ μμ μΌμͺ½ λ ΈλλΆν° μ μΌ ν° μ€λ₯Έμͺ½ λ ΈλκΉμ§ λμ΄νλ νν
π Tree Traversal : postorder
μΌμͺ½λΆν° κ²μ¬νλ, (κ°μ₯ λ§λ¨ λ Έλμμ μμν΄μ) λ§λλ λ Έλ μ‘±μ‘± κ²μ¬ μν ν μ€λ₯Έμͺ½μΌλ‘ λμ΄κ°λ νν
preorderμ λ€λ₯Έ μ μ, λ£¨νΈ λ Έλλ₯Ό κ°μ₯ λ§μ§λ§μ κ²μ¬νλ€λ μ μ΄λ€. (μ€κ°μ κ±°μΉμ§ μμ)
λ°μν