๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
the others/Algorithm

Binary Search Tree ๊ตฌํ˜„ : pre-order / in-order / post-order

by ciocio 2021. 9. 23.

๐Ÿ“Œ  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์™€ ๋‹ค๋ฅธ ์ ์€, ๋ฃจํŠธ ๋…ธ๋“œ๋ฅผ ๊ฐ€์žฅ ๋งˆ์ง€๋ง‰์— ๊ฒ€์‚ฌํ•œ๋‹ค๋Š” ์ ์ด๋‹ค. (์ค‘๊ฐ„์— ๊ฑฐ์น˜์ง€ ์•Š์Œ)

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€