二叉树是一种经典的数据结构,二话不说,上代码。。
//节点
function Node(element, left, right,parents) {
this.element = element;
this.left = left;
this.right = right;
this.parents = parents;
this.show = function() {
return this.element;
}
}
//二叉树
function BST() {
this.root = null;
//插入节点
this.insert = function(element){
let node = new Node(element, null, null);
if(this.root === null) this.root = node;
else {
let buffer = this.root;
while(true) {
if(node.element > buffer.element) {
if(buffer.right === null) {
buffer.right = node;
node.parents = buffer;
break;
} else {
buffer = buffer.right;
}
}
if(node.element <= buffer.element) {
if(buffer.left === null) {
buffer.left = node;
node.parents = buffer;
break;
} else {
buffer = buf