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樹了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注本站行業資訊頻道。
本文由 貴州做網站公司 整理發布,部分圖文來源于互聯網,如有侵權,請聯系我們刪除,謝謝!
c語言中正確的字符常量是用一對單引號將一個字符括起表示合法的字符常量。例如‘a’。數值包括整型、浮點型。整型可用十進制,八進制,十六進制。八進制前面要加0,后面...
2022年天津專場考試原定于3月19日舉行,受疫情影響確定延期,但目前延期后的考試時間推遲。 符合報名條件的考生,須在規定時間登錄招考資訊網(www.zha...
:喜歡聽,樂意看。指很受歡迎?!巴卣官Y料”喜聞樂見:[ xǐ wén lè jiàn ]詳細解釋1. 【解釋】:喜歡聽,樂意看。指很受歡迎。2. 【示例】:這是...
(相關資料圖)想必現在有很多小伙伴對于奶膘是什么意思,王一博嬰兒奶膘什么梗方面的知識都比較想要了解,那么今天小好小編就為大家收集了一些關于奶膘是什么意思,王一博嬰兒奶膘什么梗方面的知識分享給大家,希望大家會喜歡哦。奶膘,讀音[nǎi biāo],是嬰兒肥的另一種表達方式,是指已經脫離嬰兒時代,但臉看起來還是有點肉嘟嘟的,高發于圓臉和鵝蛋臉,絕不會出現于菱形臉、方臉、錐子臉中,因為屬于嬰兒肥,所以也...
中信銀行電子賬戶具體含義。中信銀行電子賬戶是指用戶通過電子渠道實名開立的,可以購買投資理財產品等指定金融產品的賬戶,屬于非面對面開立的二類銀行賬戶或三類銀行賬戶。要在中信銀行,開立電子賬戶,您必須年滿16歲,在身份證的正面和背面提供真實、完整和準確的信息,并核實手機號碼必須與綁定到該賬戶的手機號碼一致。中信銀行電子賬戶可以為用戶提供金融產品和服務,但不會向用戶發送紙質票據,用戶只能通過指定的電子渠...
a股和b股哪個好?1、a股主要面向國內投資者,而b股主要面向外國和港澳臺公民,因為b股的正式名稱是人民幣特種股票,是在中國證券證券交易所上市交易但b股公司注冊地和上市地都在中國的外資股票。在交易層面,以人民幣標明面值,以外幣認購和買賣。2、a股的手續費會比b股低。a股的成交率在0.2%左右,b股在1%左右。3、一般a股賬戶沒有開戶費,b股賬戶有開戶費。一般b股賬戶開戶費是120港幣,滬b股賬戶開戶...