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  

 

[10, 8, 3, 7, 5, 15, 11, 14, 16]

μ™Όμͺ½λΆ€ν„° κ²€μ‚¬ν•˜λ˜, (루트 λ…Έλ“œμ—μ„œ μ‹œμž‘ν•΄μ„œ) λ§Œλ‚˜λŠ” λ…Έλ“œ μ‘±μ‘± 검사 μˆ˜ν–‰ ν›„ 였λ₯Έμͺ½μœΌλ‘œ λ„˜μ–΄κ°€λŠ” ν˜•νƒœ

 

 

πŸ“  Tree Traversal : inorder  

 

inorder λ™μž‘ κ³Όμ •
[3, 5, 7, 8, 10, 11, 14, 15, 16]

제일 μž‘μ€ μ™Όμͺ½ λ…Έλ“œλΆ€ν„° 제일 큰 였λ₯Έμͺ½ λ…Έλ“œκΉŒμ§€ λ‚˜μ—΄ν•˜λŠ” ν˜•νƒœ

 

 

πŸ“  Tree Traversal : postorder  

 

[5, 7, 3, 8, 14, 11, 16, 15, 10]

μ™Όμͺ½λΆ€ν„° κ²€μ‚¬ν•˜λ˜, (κ°€μž₯ 말단 λ…Έλ“œμ—μ„œ μ‹œμž‘ν•΄μ„œ) λ§Œλ‚˜λŠ” λ…Έλ“œ μ‘±μ‘± 검사 μˆ˜ν–‰ ν›„ 였λ₯Έμͺ½μœΌλ‘œ λ„˜μ–΄κ°€λŠ” ν˜•νƒœ

preorder와 λ‹€λ₯Έ 점은, 루트 λ…Έλ“œλ₯Ό κ°€μž₯ λ§ˆμ§€λ§‰μ— κ²€μ‚¬ν•œλ‹€λŠ” 점이닀. (쀑간에 κ±°μΉ˜μ§€ μ•ŠμŒ)

λ°˜μ‘ν˜•