function binaryTree(){
function Node(key){
this.key=key;
this.left=null;
this.right=null;
}
var root=null;
var insertTree=function(root,newNode){
if(newNode.key<root.key){
if(root.left===null){
root.left=newNode;
}else{
insertTree(root.left,newNode);
}
}else{
if(newNode.key>root.key){
if(root.right===null){
root.right=newNode;
}else{
insertTree(root.right,newNode);
}
}
}
}
var centerOrderTree=function(root,callback){
if(root!=null){
centerOrderTree(root.left,callback);
callback(root.key);
centerOrderTree(root.right,callback);
}
}
var preOrderTree=function(root,callback){
if(root!=null){
callback(root.key);
preOrderTree(root.left,callback);
preOrderTree(root.right,callback);
}
}
var lastOrderTree=function(root,callback){
if(root!=null){
lastOrderTree(root.left,callback);
lastOrderTree(root.right,callback);
callback(root.key);
}
}
var searchMin=function(root){
if(root==null){
return;
}
while(root && root.left!==null){
root=root.left;
}
return root.key;
}
var searchMax=function(root){
if(!root){
return;
}
while(root && root.right!==null){
root=root.right;
}
return root.key;
}
var searchNode=function(root,key){
if(!root){
return;
}
if(key<root.key){
return searchNode(root.left,key)
}else if(key>root.key){
return searchNode(root.right,key)
}else{
return true;
}
}
var findMinNode=function(root){
if(root==null){
return null;
}
while(root && root.left!==null){
root=root.left;
}
return root;
}
var removeNode=function(root,key){
if(root==null){
return null;
}
if(key<root.key){
root.left=removeNode(root.left,key);
return root;
}else if(key>root.key){
root.right=removeNode(root.right,key);
return root;
}else{
if(root.left==null&&root.right==null){
root=null;
return root;
}
if(root.left==null){
root=root.right;
return root;
}
else if(root.right==null){
root=root.left;
return root;
}else{
var minNode=findMinNode(root.right);
root.key=minNode.key;
root.right=removeNode(root.right,minNode.key);
return root;
}
}
}
//生成二叉树
this.generateTree=function(key){
var newNode=new Node(key);
if(root===null){
root=newNode;
}else{
insertTree(root,newNode);
}
}
//中序遍历二叉树
this.centerSort=function(callback){
centerOrderTree(root,callback);
}
//前序遍历二叉树
this.preSort=function(callback){
preOrderTree(root,callback);
}
// 后序遍历
this.lastSort=function(callback){
lastOrderTree(root,callback)
}
//查找最小值
this.min=function(){
return searchMin(root);
}
//查找最大值
this.max=function(){
return searchMax(root);
}
//查找某值是否存在
this.search=function(key){
return searchNode(root,key);
}
this.remove=function(key){
return removeNode(root,key);
}
}
var b=[1,3,2,6,5,234,10];
var t=new binaryTree();
b.forEach((item)=>{
t.generateTree(item);
})
console.log(t.remove(2));
console