效果图:
二叉树容器更快捷的对数据: 增 删 改 查:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>二叉树容器</title>
</head>
<body>
<script>
let BST = (function(){
let root = Symbol();
class Node{
constructor(key){
this.key = key;
this.left = null;
this.right = null;
}
}
function insertNode(root,node){
if(node.key < root.key){
if(root.left){
insertNode(root.left,node)
}else{
root.left = node;
}
}else{
if(root.right){
insertNode(root.right,node)
}else{
root.right = node;
}
}
}
function inOrderTraverseNode(root,arr){
if( !root ) return;
inOrderTraverseNode(root.left,arr)
arr.push(root.key);
inOrderTraverseNode(root.right,arr)
}
function preOrderTraverseNode(root,arr){
if( !root ) return;
arr.push(root.key);
inOrderTraverseNode(root.left,arr)
inOrderTraverseNode(root.right,arr)
}
function postOrderTraverseNode(root,arr){
if( !root ) return;
inOrderTraverseNode(root.left,arr)
inOrderTraverseNode(root.right,arr)
arr.push(root.key);
}
function ishas(root,key){
if(key == root.key)return true;
if(key < root.key){
if(root.left) return ishas(root.left,key)
else return false;
}else{
if(root.right)return ishas(root.right,key);
else return false;
}
}
function removeNode(root,key,zhong){
if(key == root.key){
let left = root.left;
let right = root.right;
if(right){
while(right.left){
right = right.left;
}
right.left = left;
}
if(zhong !=undefined){
right? root = root.right : root = root.left;
};
return root;
};
if(key < root.key){
if(root.left){
let top = removeNode(root.left,key)
if(top.right){
root.left= top.right;
}else if(top){
root.left= top.left;
}
return false
}else return false;
}
if(key > root.key){
if(root.right){
let top = removeNode(root.right,key)
if(top.right){
root.right= top.right;
}else if(top){
root.right= top.left;
}
return false
}else return false;
}
return root
}
return class{
constructor(){
this[root] = null;
}
insert(key){
let node = new Node(key),
Root = this[root];
if(!Root){
this[root] = node;
}else{
insertNode(Root, node);
}
}
inOrderTraverse(){
let arr = [];
inOrderTraverseNode(this[root], arr);
return arr;
}
getMax(){
let Root = this[root];
if(!Root)return undefined;
while (Root.right){
Root = Root.right
}
return Root.key;
}
getMin(){
let Root = this[root];
if(!Root)return undefined;
while (Root.left){
Root = Root.left
}
return Root.key;
}
has(key){
return ishas(this[root],key);
}
remove(key){
this[root] = removeNode(this[root],key,this[root].key)
return this[root];
}
}
})();
let bst = new BST;
bst.insert(20);
bst.insert(10);bst.insert(8); bst.insert(12);bst.insert(11);bst.insert(13);
bst.insert(25);bst.insert(31);bst.insert(22);bst.insert(21);bst.insert(23);bst.insert(28);
console.log(bst.inOrderTraverse());
console.log(bst.remove(20));
console.log(bst.inOrderTraverse());
</script>
</body>
</html>