重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
这期内容当中小编将会给大家带来有关JavaScript中怎么构建一个avl树,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
创新互联主营弋阳网站建设的网络公司,主营网站建设方案,重庆App定制开发,弋阳h5成都微信小程序搭建,弋阳网站营销推广欢迎弋阳等地区企业咨询
function Node(value) {
this.value = value;
this.left = this.right = null;
this.height = 0;
}
function height(node) {
return node ? node.height : 0;
}
function rotateLeft(node) {
const right = node.right;
node.right = right.left;
right.left = node;
node.height = Math.max(height(node.left, node.right)) + 1;
right.height = Math.max(height(right.left, right.right)) + 1;
return right;
}
function rotateRight(node) {
const left = node.left;
node.left = left.right;
left.right = node;
node.height = Math.max(height(node.left, node.right)) + 1;
left.height = Math.max(height(left.left, left.right)) + 1;
return left;
}
function rotateLeftRight(node) {
node.left = rotateLeft(node.left);
return rotateRight(node);
}
function rotateRightLeft(node) {
node.right = rotateRight(node.right);
return rotateLeft(node);
}
function avlTreeInsert(node, value) {
if (!node) {
node = new Node(value);
} else if (value > node.value) {
node.right = avlTreeInsert(node.right, value);
if (height(node.right) - height(node.left) == 2) {
if (value > node.right.value) {
node = rotateLeft(node);
} else {
node = rotateRightLeft(node);
}
}
} else if (value < node.value){
node.left = avlTreeInsert(node.left, value);
if (height(node.right) - height(node.left) == 2) {
if (value > node.left.value) {
node = rotateRight(node);
} else {
node = rotateLeftRight(node);
}
}
}
node.height = Math.max(height(node.right), height(node.left)) + 1;
return node;
}
(function test() {
let i = 0;
let data = [];
while(i < 100) {
data.push(i++);
}
i = 0;
let root;
while(i < data.length) {
root = avlTreeInsert(root, data[i++]);
}
const queue = [root];
let current;
while(current = queue.shift()) {
console.log(current.value, height(current.right) - height(current.left));
queue.push(current.right);
queue.push(current.left);
}
console.log(root);
console.log(find(root ,99))
})();
function find(node, value) {
if (!node) {
return null;
}
if (node.value === value) {
return node;
}
return find(node.value > value ? node.left : node.right, value);
}
上述就是小编为大家分享的JavaScript中怎么构建一个avl树了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注创新互联行业资讯频道。