Convert an sorted array to a binary search tree

//asume we have Tree() to generate a BST
//each tree has a value, a left pointer and a right pointer
var walker = function(input){
  //base
  if(input.length===0){
    return;
  }
  if(input.length===1){
    return new Tree(input[0]);
  }

  //iter
  var middle_index = Math.floor(input.length/2);
  var left = input.slice(0, middle_index);
  var right = input.slice(middle_index+1, input.length);

  var tree = new Tree(input[middle_index]);
  tree.left = walker(left);
  tree.right = walker(right);

  return tree;
};

walker([1,2,3,4,5,6,7,8,9]);
Advertisements
Standard