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.getMax = function () {
if (this.root == null) {
return;
}
let currentNode = this.root;
while (currentNode.right) {
currentNode = currentNode.right;
}
return currentNode;
}
求最小节点
Tree.prototype.getMin = 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;
//如果currentNode指向得值不为空 且对应得value值和要找得值不相同
while (currentNode && currentNode.value != value) {
//如果value比节点得值小 ,那么currentNode 指向 当前节点得左节点
if (value < currentNode.value) {
currentNode = currentNode.left;
} else {
// //如果value比节点得值小 ,那么currentNode 指向 当前节点得右节点
currentNode = currentNode.right;
}
}
return currentNode;
}