//封装二叉搜索树
function BinarySearchTree() {
function Node(key) {
this.key=key
this.left=null
this.right=null
}
//根节点属性
this.root=null
//insert方法 向外暴露给用户使用
BinarySearchTree.prototype.insert=function (key) {
//1.先根据key创建节点
let newNode=new Node(key)
//2.判断根节点是否有值
if(this.root==null){
this.root=newNode
}else{
this.insertNode(this.root,newNode)
}
}
BinarySearchTree.prototype.insertNode=function (node,newNode) {
//1.向左搜索 2.向右搜索
if(newNode.key<node.key){
if(node.left==null){
node.left=newNode
}else{
this.insertNode(node.left,newNode)
}
}else {
if(node.right==null){
node.left=newNode
}else{
this.insertNode(node.right,newNode)
}
}
}
}
二叉搜索树(insert方法)
最新推荐文章于 2022-04-28 17:32:44 发布