트리 Tree

Rudy·2022년 12월 8일
0

트리 Tree

class Node {
  constructor(value){
    this.value = value;
    this.left = null;
    this.right = null;
  }
}

class BinarySearchTree {
  constructor(){
    this.root = null;
  }
}

let tree = new BinarySearchTree();
tree.root = new Node(10);
tree.root.right = new Node(15);
tree.root.left = new Node(7);
tree.root.left.right = new Node(9)

이진 검색 트리

class Node {
  constructor(value){
    this.value = value;
    this.left = null;
    this.right = null;
  }
}

class BinarySearchTree {
  constructor(){
    this.root = null;
  }
  insert(value){
    let newNode = new Node(value);
    if(this.root === null){
        this.root = newNode;
        return this;
    } else{
      let current = this.root;
      console.log(current,"current")
      while(true){
        if(value === current.value) return undefined;
        if(value < current.value){
            if(current.left === null){
              current.left = newNode;
              return this;
            }else{
              current = current.left;
            }
        } else if(value > current.value){
          if(current.right === null){
            current.right = newNode;
            return this;
          } else{
            current = current.right;
          }
        }        
      }
    }  
  }
}

let tree = new BinarySearchTree();
tree.insert(10);
tree.insert(5);
tree.insert(13)
tree.insert(11)
tree.insert(2)
tree.insert(16)
tree.insert(7)
// tree.insert(13)
// tree.root = new Node(10);
// tree.root.right = new Node(15);
// tree.root.left = new Node(7);
// tree.root.left.right = new Node(9)
console.log(tree,"tree")

이진 검색 트리 리팩토링

class Node {
  constructor(value){
    this.value = value;
    this.left = null;
    this.right = null;
  }
}

class BinarySearchTree {
  constructor(){
    this.root = null;
  }
  insert(value){
    let newNode = new Node(value);
    if(this.root === null){
        this.root = newNode;
        return this;
    } else{
      let current = this.root;
      console.log(current,"current")
      while(true){
        if(value === current.value) return undefined;
        if(value < current.value){
            if(current.left === null){
              current.left = newNode;
              return this;
            }
              current = current.left;            
        } else {
          if(current.right === null){
            current.right = newNode;
            return this;
          } 
            current = current.right;          
        }        
      }
    }  
  }
}

let tree = new BinarySearchTree();
tree.insert(10);
tree.insert(5);
tree.insert(13)
tree.insert(11)
tree.insert(2)
tree.insert(16)
tree.insert(7)
// tree.insert(13)
// tree.root = new Node(10);
// tree.root.right = new Node(15);
// tree.root.left = new Node(7);
// tree.root.left.right = new Node(9)
console.log(tree,"tree")
profile
주니어 개발자

0개의 댓글