이진 검색 트리 Find

Rudy·2022년 12월 8일
1

이진 검색 트리 Find

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;          
        }        
      }
    }  
  }
  find(value){
    if(this.root === null) return true;
    let current = this.root,
        found = false;
    while(current && !found){
          if(value < current.value){
            current = current.left;
          } else if(value > current.value){
              current = current.right;
          } else{
              found = true;
          }
    }
     if(!found) return undefined;
     return current;
  }
   contains(value){
    if(this.root === null) return true;
    let current = this.root,
        found = false;
    while(current && !found){
          if(value < current.value){
            current = current.left;
          } else if(value > current.value){
              current = current.right;
          } else{
              return  true;
          }
    }
     return false;
  }
}

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)
const test = tree.find(11)
tree.find(11)



profile
주니어 개발자

0개의 댓글