function BST(){
let root = null;//初始化为null;
//节点兑现
function Node(value,left,right){
this.value = value;
this.left = left;
this.right = right;
}
//插入节点方法
function insertNode(parentNode,newNode){
if(newNode.value>parentNode.value){//大于父节点-设为右子树
//如果已经有右子树 递归调用
if(parentNode.right){
insertNode(parentNode.right,newNode);
}else{
parentNode.right = newNode;
}
}else{//小于父节点-设为左子树
if(parentNode.left){
insertNode(parentNode.left,newNode);
}else{
parentNode.left = newNode;
}
}
}
//获取root
this.getRoot = ()=>{
return root;
}
//实例的插入节点方法
this.insert = (value)=>{
let node = new Node(value,null,null);
if(root==null){
root = node
}//根节点为空 直接将node赋值给根节点
else{
insertNode(root,node);
}
};
//中序遍历 -先查左子树 再查中间节点 再查右子树 - 返回按顺序排列的值
this.inOrder = (node,callBack)=>{
if(node!=null){//如果node不为空
this.inOrder(node.left,callBack);
callBack(node.value);
this.inOrder(node.right,callBack);
}
}
//前序遍历 先查询中间节点 在查询左子树 再查询右子树
this.preOrder = (node,callBack)=>{
if(node!=null){
callBack(node.value);
this.preOrder(node.left,callBack);
this.preOrder(node.right,callBack);
}
}
//后续遍历 先查询左子树 再查询右子树 再查询中间节点
this.postOrder = (node,callBack)=>{
if(node!=null){
this.postOrder(node.left,callBack);
this.postOrder(node.right,callBack);
callBack(node.value);
}
}
//查找最小值
this.getMIn = (node)=>{
//一直在左子树上查找到最后一个
if(node.left!=null){
while(node&&node.left){
node = node.left;
}
return node.value;
}
return node.value||null;
}
//查找最大值 - 一直在右子树上查找
this.getMax = (node)=>{
if(node!=null){
while(node&&node.right){
node = node.right;
}
return node.value;
}
return node.value||null;
}
//查找是否存在指定的值
this.getValue = (node,value)=>{
if(node==null){
return false;
}
//如果大于当前节点值 从右子树上查找
if(value>node.value){
return this.getValue(node.right,value)
}else if(value<node.value){
return this.getValue(node.left,value);
}else{//等于的话直接返回true 查找到了
return true;
}
}
}
printLog = (value) => {
console.info(value);
}
var sArr = [8, 3, 10, 1, 5, 14, 4, 6, 13];
var bstIns = new BST();
sArr.forEach((item) => {
bstIns.insert(item);
});
bstIns.inOrder(bstIns.getRoot(),printLog);
var minValue = bstIns.getMIn(bstIns.getRoot());
printLog(minValue);
printLog(bstIns.getValue(bstIns.getRoot(),6));
printLog(bstIns.getValue(bstIns.getRoot(),11));