javascript BST-从阵列

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript BST-从阵列相关的知识,希望对你有一定的参考价值。

let node = function(data) {
  this.data = data;
  this.left = null;
  this.right = null;
}

let bst = function() {
  this.root = null;
}

bst.prototype.sortedArrToBST = function(arr, start, end) {
  // base
  if (start > end) return null;
  
  // get middle element and make it root
  let mid = Math.floor((start + end) / 2);
  let nd = new node(arr[mid]);
  
  // recursively construct left subtree and make it left child
  nd.left = this.sortedArrToBST(arr, start, mid - 1);
  
  // recursively construct right subtree and make it right child
  nd.right = this.sortedArrToBST(arr, mid + 1, end);
  return nd;
}

bst.prototype.preOrder = function(node) {
  if (!node) return null;
  console.log(node.data);
  this.preOrder(node.left);
  this.preOrder(node.right);
}

let tree = new bst();
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const n = arr.length;
let root = tree.sortedArrToBST(arr, 0, n - 1);
console.log('preOrder');
tree.preOrder(root);

以上是关于javascript BST-从阵列的主要内容,如果未能解决你的问题,请参考以下文章

javascript 从阵列随机随机播放

JavaScript 从阵列2中删除重复值

JavaScript 从阵列中删除重复值

Javascript 显示来自本地存储阵列的数据问题

JavaScript之BST

javascript 遍历有序BST