//封装二叉搜索树
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.right=newNode
}else{
this.insertNode(node.right,newNode)
}
}
}
//先序遍历
BinarySearchTree.prototype.preOrderTraversal=function (handler) {
this.preOrderTraversalNode(this.root,handler)
}
BinarySearchTree.prototype.preOrderTraversalNode=function (node,handler) {
if(node!=null){
//打印经过的节点
handler(node.key)
//1.遍历左子树
this.preOrderTraversalNode(node.left,handler)
//2.遍历右子树
this.preOrderTraversalNode(node.right,handler)
}
}
//删除节点
BinarySearchTree.prototype.remove=function (key) {
//1.找到要删除的节点
//1.1保存子节点,父节点,两者之间的关系
let current=this.root
let parent=null
let isLeft=true
while(current.key!=key){
parent=current
if(current.key<key){
current=current.left
isLeft=true
}else{
current=current.right
isLeft=false
}
//如果找到叶子节点还没找到,说明要删除的节点不存在,返回false
if(current==null) return false
}
//2.根据找到的节点进行操作
//2.1 删除的节点是叶子节点
if(current.left==null&¤t.right==null){
if(current==this.root){
this.root=null
}else if(isLeft){
parent.left=null
}else if(isLeft){
parent.right=null
}
}
//2.2 删除的节点是有一个叶子节点
else if(current.right==null){
if(current=this.root){
this.root=current.left
}else if(isLeft){
parent.left=current.left
}else if(!isLeft){
parent.right=current.left
}
}else if(current.left==null){
if(current==this.root){
this.root=current.right
}else if(isLeft){
parent.left=current.right
}else if(!isLeft){
parent.right=current.right
}
}
//2.3删除的节点有两个子节点
else{
let succssor=this.getSuccssor(current)
if(current==this.root){
this.root=succssor
}else if(isLeft){
parent.left=succssor
}else if(!isLeft){
parent.right=succssor
}
succssor.left=current.left
}
}
BinarySearchTree.prototype.getSuccssor=function (delNode) {
//1.定义变量,保存找到的后继,后继父节点
let succssor=delNode
let current=delNode.right
let succssorParent=delNode
//2.循环查找
while(current!=null){
succssorParent=succssor
succssor=current
current=current.left
}
//3.判断查找的后继节点是否直接就是delNode的right节点
if(succssor != delNode.right){
succssorParent.left = succssor.right
succssor.right=delNode.right
}
return succssor
}
}
//测试代码
let bst = new BinarySearchTree()
bst.insert(11)
bst.insert(7)
bst.insert(15)
bst.insert(5)
bst.insert(3)
bst.insert(9)
bst.insert(8)
bst.insert(10)
bst.insert(13)
bst.insert(12)
bst.insert(14)
bst.insert(20)
bst.insert(18)
bst.insert(6)
bst.insert(25)
let resultString=""
bst.remove(11)
bst.remove(7)
bst.remove(5)
bst.preOrderTraversal(function (key) {
resultString+=key+' '
})
console.log(resultString)
二叉树的删除操作
最新推荐文章于 2022-03-28 16:13:26 发布