우리는 AVL 트리에 노드를 삽입하는 방법을 배울 수 있습니다. AVL 트리의 삽입은 BST와 동일하며, 트리 아래로 이동할 때마다 삽입 중에 밸런스 트리라는 추가 단계를 수행하면 됩니다.
이것은 우리가 이전에 이미 본 균형 계수를 계산해야 합니다. 그리고 구성에 따라 적절한 회전 방법을 호출해야 합니다. 위의 설명 덕분에 매우 직관적입니다.
재귀 호출을 위한 클래스 메서드와 도우미 함수를 다시 만듭니다.
예시
insert(data) {
let node = new this.Node(data);
// Check if the tree is empty
if (this.root === null) {
// Insert as the first element
this.root = node;
} else {
insertHelper(this, this.root, node);
}
} 도우미 방법
function insertHelper(self, root, node) {
if (root === null) {
root = node;
} else if (node.data < root.data) {
// Go left!
root.left = insertHelper(self, root.left, node);
// Check for balance factor and perform appropriate rotation
if (root.left !== null && self.getBalanceFactor(root) > 1) {
if (node.data > root.left.data) {
root = rotationLL(root);
} else {
root = rotationLR(root);
}
}
} else if (node.data > root.data) {
// Go Right! root.
right = insertHelper(self, root.right, node);
// Check for balance factor and perform appropriate rotation
if (root.right !== null && self.getBalanceFactor(root) < -1) {
if (node.data > root.right.data) {
root = rotationRR(root);
} else {
root = rotationRL(root);
}
}
}
return root;
} −
를 사용하여 이것을 테스트할 수 있습니다.예시
let AVL = new AVLTree(); AVL.insert(10); AVL.insert(15); AVL.insert(5); AVL.insert(50); AVL.insert(3); AVL.insert(7); AVL.insert(12); AVL.inOrder();
출력
이것은 출력을 줄 것입니다 -
3 5 7 10 12 15 50