javascript binarySearchTree由plastikaweb创建 - https://repl.it/@plastikaweb/binarySearchTree

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript binarySearchTree由plastikaweb创建 - https://repl.it/@plastikaweb/binarySearchTree相关的知识,希望对你有一定的参考价值。

// Binary search tree

function BST(value) {
  this.value = value;
  this.left = null;
  this.right = null;
}

BST.prototype.insert = function(value) {
  if (value <= this.value) {
    if (!this.left) {
      this.left = new BST(value);
    } else {
      this.left.insert(value);
    }
  } else {
    if (!this.right) {
      this.right = new BST(value);
    } else {
      this.right.insert(value);
    }
  }
};

BST.prototype.contains = function(value) {
  if (value === this.value) return true;
  else if (value < this.value) {
    if (!this.left) return false;
    else return this.left.contains(value);
  } else if (value > this.value) {
    if (!this.right) return false;
    else return this.right.contains(value);
  }
};

BST.prototype.depthFirstTraversal = function(iteratorFunc, order) {
  if (order === 'pre-order') iteratorFunc(this.value);
  if (this.left) this.left.depthFirstTraversal(iteratorFunc, order);
  if (order === 'in-order') iteratorFunc(this.value);
  if (this.right) this.right.depthFirstTraversal(iteratorFunc, order);
  if (order === 'post-order') iteratorFunc(this.value);
};

BST.prototype.breadthFirstTraversal = function(iteratorFunc) {
  var queue = [this];
  while (queue.length) {
    var treeNode = queue.shift();
    iteratorFunc(treeNode.value);
    if (treeNode.left) queue.push(treeNode.left);
    if (treeNode.right) queue.push(treeNode.right);
  }
};

BST.prototype.getMinVal = function() {
  if (this.left) return this.left.getMinVal();
  else return this.value;
};

BST.prototype.getMaxVal = function() {
  if (this.right) return this.right.getMaxVal();
  else return this.value;
};

var bst = new BST(50);
bst.insert(25);
bst.insert(15);
bst.insert(55);
bst.insert(60);
bst.insert(59);
bst.insert(20);
bst.insert(45);
bst.insert(35);
bst.insert(65);
bst.insert(58);
bst.insert(10);

function log(value) {
  console.log(value);
}
// bst.depthFirstTraversal(log, 'pre-order');
// console.log('-');
// bst.depthFirstTraversal(log, 'in-order');
// console.log('-');
// bst.depthFirstTraversal(log, 'post-order');
// console.log('-');
// bst.breadthFirstTraversal(log);
console.log(bst.getMinVal());
console.log(bst.getMaxVal());

以上是关于javascript binarySearchTree由plastikaweb创建 - https://repl.it/@plastikaweb/binarySearchTree的主要内容,如果未能解决你的问题,请参考以下文章

javascript JavaScript isset()等效: - JavaScript

JavaScript 使用JavaScript更改CSS(JavaScript)

JavaScript之基础-1 JavaScript(概述基础语法)

前端基础-JavaScript的基本概述和语法

JavaScript

JavaScript