Метод вставки BST JS Получение бесконечного цикла - PullRequest
0 голосов
/ 18 февраля 2020

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

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

insert(val) {
    var node = new Node(val);
    if(!this.root) {
      this.root = node;
      return this;
    } else{
       var root = this.root;
      while(root) {
         if(val === root.value) return undefined;
          if(val < root.value) {
             if(!root.left) {
              root.left = node;
               return this;
             } else{
               root = root.left;
             }
          } else if(val > root.value) {
                if(!root.right) {
                  root.right = node;
                  return this;
                } else{
                  root = root.right;
                }
              }
           }
      }
   }
}

   var bts = new BinarySearchTree();
   
   bts.insert(100);

В этом методе большую часть времени я получаю бесконечное l oop, я понятия не имею, почему, может кто-нибудь помочь мне найти ошибку в моем коде, Иногда этот метод работает нормально, но иногда бесконечный l oop. Спасибо

...