这是有上期,没下期,学习看心情,更新看随机的老王的学习笔记,好好看,没有下期了……
树
将输入的第一个数作为根结点,之后插入的每一个数若比当前节点大,则插入在当前结点的右侧,否则插入到当前结点的左侧。
例如这组数[22,19,114,514,1919,14,2]
当前的(根)节点为22
19比当前节点要小,于是插入到22的左边
接着是114,比根结点要大,于是放在根节点的右边
接着是514,比根结点要大,于是放在根节点的右边;并且514比根结点的右节点114还要大,所以放在114的右边
接着是1919,比根结点、根结点右节点(114)和右节点的右节点(514)都还要大,所以放在514的右边
接着是14,14比根结点22要小,并且比根结点的左节点(19)还要小,所以放在19的左边
最后就是2,比所有的节点都小,所以放在14的左边
附上代码:
function Node(element,left,right) {
this.element = element;
this.left=left;
this.right=right;
this.next = null;
this.show = function () {
return this.element;
};
}
function BST() {
this.root = null;
this.insert=function (element) {
var node = new Node(element,null,null);
if(this.root==null){
this.root=node;
}else{
var parent = this.root;
while(true){
var buffer = parent;
if(node.element>this.root.element){
parent = parent.right;
if(parent==null){
buffer.right = node;
break;
}
}else{
parent = parent.left;
if(parent==null){
buffer.left = node;
break;
}
}
}
}
}
}
var bst = new BST();
bst.insert(12);
bst.insert(9);
bst.insert(114);
bst.insert(514);
bst.insert(14);
console.log(bst);