function Node(value,left,right){
this.value = value;
this.left=left;
this.right=right;
}
function Tree(){
this.root = null;
}
//二叉树代码实现,添加节点
Tree.prototype.add=function(value){
//判断树有没有根节点
let node = new Node(value,null,null);
if(this.root==null){
//没有根节点 新创建的节点作为树的根节点
this.root=node;
return ;
}else{
let currentNode = this.root;
let parentNode =null;
while(true){
if(value<currentNode.value){
parentNode=currentNode;//父节点指向currentNode
currentNode=currentNode.left;//currentNode往下移动
if(currentNode==null){//如果currentNode指向空了 那么就需要把节点挂到这个位置
parentNode.left=node;
break;
}
}else if(value>currentNode.value){
parentNode = currentNode;
currentNode=currentNode.right;
if (!currentNode) {
parentNode.right = node;
break;
}
}else{
break;
}
}
}
}
求最大节点
Tree.prototype.getMaxNode=function(){
if(this.root==null){
return;
}
let currentNode = this.root;
while(currentNode.right){
currentNode=currentNode.right;
}
return currentNode;
}
求最小节点
Tree.prototype.getMinNode=function(){
if(this.root==null){
return;
}
let currentNode = this.root;
while(currentNode.left){
currentNode=currentNode.left;
}
return currentNode;
}
查找value对应的节点,找到则返回节点,没找到则返回null
Tree.prototype.search=function(value){
if(this.root==null){
return null;
}
let currentNode = this.root;
while(currentNode&¤tNode.value!=value){
if(value<currentNode.value){
currentNode=currentNode.left;
}else{
currentNode=currentNode.right;
}
}
return currentNode;
}