当前位置:网站首页>AVL balanced binary search tree
AVL balanced binary search tree
2022-07-01 15:52:00 【Yan Ran】
Binary search tree (BST) Although it can shorten the search efficiency , but If the data is in order or close to order ,BST take Degenerate into a single tree , At this point, searching for elements is equivalent to The order sheet Search elements in , inefficiency .
At this time, if we can ensure that the absolute value of the height difference between the left and right subtrees of each node does not exceed 1, You can reduce the height of the tree , This reduces the average search length . therefore AVL With this mission was born .
One 、AVL
In a binary tree , If the height difference of the subtree of each node is 0、1 or -1, Call this tree a balanced binary tree , namely AVL.
Two 、 Balanced binary trees
If the insert or delete operation results in AVL The imbalance of , Then we need to perform a rotation operation to rebalance the tree . Rotation operations mainly include LL、RR、LR、RL Four types .
1、LL
towards The left child in the left subtree inserts New nodes lead to imbalance , At this time need Right hand operation :

After rotation, the balanced binary tree will B As new root, take E Node and A.left Connected to a , then A And B.right Connected to a , Finally get a new AVL.
private void balanceLL(AVLTreeNode<E> A, TreeNode<E> parentOfA){
TreeNode<E> B = A.left;
if(A == root){
root = B;
}else{
if(parentOfA.left == A){
parentOfA.left = B;
}else{
parentOfA.right = B;
}
}
A.left = B.right;
B.right = A;
updateHeight((AVLTreeNode<E>) A);
2、RR
and LL contrary , towards The right child in the right subtree inserts Imbalance caused by new nodes , At this time need left-handed operation :

private void balanceRR(TreeNode<E> A, TreeNode<E> parentOfA){
TreeNode<E> B =A.right;
if(A == root){
root = B;
}else{
if(parentOfA.left == A){
parentOfA.left = B;
}else{
parentOfA.right = B;
}
}
A.right = B.left;
B.left = A;
updateHeight((AVLTreeNode<E>)A);
updateHeight((AVLTreeNode<E>)B);
}3、LR
Left son left rotation , Root node dextral :

private void balanceLR(TreeNode<E> A, TreeNode<E> parentOfA){
TreeNode<E> B = A.left;
TreeNode C = B.right;
if(A == root){
root = C;
}else{
if(parentOfA.left == A){
parentOfA.left = C;
}else {
parentOfA.right = C;
}
}
A.left = C.right;
B.right = C.left;
C.left = B;
C.right = A;
updateHeight((AVLTreeNode<E>)A);
updateHeight((AVLTreeNode<E>)B);
updateHeight((AVLTreeNode<E>)C);
}4、RL
Right son right rotation , Left rotation of root node :

private void balanceRL(TreeNode<E> A, TreeNode<E> parentOfA){
TreeNode<E> B = A.right;
TreeNode<E> C = B.left;
if(A == root){
root = C;
}else{
if(parentOfA.left == A){
parentOfA.left = C;
}else{
parentOfA.right = C;
}
}
A.right = C.left;
B.left = C.right;
C.left = A;
C.right = B;
updateHeight((AVLTreeNode<E>)A);
updateHeight((AVLTreeNode<E>)B);
updateHeight((AVLTreeNode<E>)C);
}3、 ... and 、Java Realization AVLTree class
AVLTree Class inheritance BST class .
public class AVLTree<E extends Comparable<E>> extends BST<E>{
public AVLTree() {
}
public AVLTree(E[] objects) {
super(objects);
}
// Insertion method and BST In the same way , Just check the balance after each addition
@Override
public boolean insert(E e){
boolean success = super.insert(e);
if(!success){
return false;
}else{
balancePath(e); // Check whether balancing operation is required
}
return true;
}
private void updateHeight(AVLTreeNode<E> node){
if(node.left == null && node.right == null){
node.height = 0;
}else if(node.left == null){
node.height = 1 + ((AVLTreeNode<E>)(node.right)).height;
}else if(node.right == null){
node.height = 1 + ((AVLTreeNode<E>)(node.left)).height;
}else
node.height = 1 + Math.max(((AVLTreeNode<E>)(node.right)).height,((AVLTreeNode<E>)(node.left)).height);
}
// Balance the nodes on a path
private void balancePath(E e){
java.util.ArrayList<TreeNode<E>> path = path(e); // Get contains e The path from the node of to the root node
for(int i = path.size() - 1; i >= 0; i--){
AVLTreeNode<E> A = (AVLTreeNode<E>)(path.get(i));
updateHeight(A); // Update height
AVLTreeNode<E> parentOfA = (A == root) ? null : (AVLTreeNode<E>)(path.get(i - 1));
switch(balanceFactor(A)){ // Check the balance factor , Check if rotation is required
case -2 :
if(balanceFactor((AVLTreeNode<E>)A.left) <= 0){
balanceLL(A,parentOfA);
}else{
balanceLR(A,parentOfA);
}
break;
case +2 :
if(balanceFactor((AVLTreeNode<E>)A.right) >= 0){
balanceRR(A, parentOfA);
}else{
balanceRL(A, parentOfA);
}
}
}
}
private int balanceFactor(AVLTreeNode<E> node){
if(node.left == null){
return -node.height;
}else if(node.left == null){
return +node.height;
}else
return ((AVLTreeNode<E>)node.right).height - ((AVLTreeNode<E>)node.left).height;
}
private void balanceLL(AVLTreeNode<E> A, TreeNode<E> parentOfA){
TreeNode<E> B = A.left;
if(A == root){
root = B;
}else{
if(parentOfA.left == A){
parentOfA.left = B;
}else{
parentOfA.right = B;
}
}
A.left = B.right;
B.right = A;
updateHeight((AVLTreeNode<E>) A);
updateHeight((AVLTreeNode<E>) B);
}
private void balanceLR(TreeNode<E> A, TreeNode<E> parentOfA){
TreeNode<E> B = A.left;
TreeNode C = B.right;
if(A == root){
root = C;
}else{
if(parentOfA.left == A){
parentOfA.left = C;
}else {
parentOfA.right = C;
}
}
A.left = C.right;
B.right = C.left;
C.left = B;
C.right = A;
updateHeight((AVLTreeNode<E>)A);
updateHeight((AVLTreeNode<E>)B);
updateHeight((AVLTreeNode<E>)C);
}
private void balanceRR(TreeNode<E> A, TreeNode<E> parentOfA){
TreeNode<E> B =A.right;
if(A == root){
root = B;
}else{
if(parentOfA.left == A){
parentOfA.left = B;
}else{
parentOfA.right = B;
}
}
A.right = B.left;
B.left = A;
updateHeight((AVLTreeNode<E>)A);
updateHeight((AVLTreeNode<E>)B);
}
private void balanceRL(TreeNode<E> A, TreeNode<E> parentOfA){
TreeNode<E> B = A.right;
TreeNode<E> C = B.left;
if(A == root){
root = C;
}else{
if(parentOfA.left == A){
parentOfA.left = C;
}else{
parentOfA.right = C;
}
}
A.right = C.left;
B.left = C.right;
C.left = A;
C.right = B;
updateHeight((AVLTreeNode<E>)A);
updateHeight((AVLTreeNode<E>)B);
updateHeight((AVLTreeNode<E>)C);
}
// and BST The deletion method in is the same , Just need to judge whether it is balanced
@Override
public boolean delete(E element){
if (root == null) {
return false;
}
TreeNode<E> parent = null;
TreeNode<E> current = root;
while(current != null){
if(element.compareTo(current.element) < 0){
parent = current;
current = current.left;
}else if(element.compareTo(current.element) > 0){
parent = current;
current = current.right;
}else break;
}
if(current == null){
return false;
}
if(current.left == null){
if(parent == null){
root = current.right;
}else {
if(element.compareTo(parent.element) < 0){
parent.left = current.right;
}else{
parent.right = current.right;
}
balancePath(parent.element);
}
}else{
TreeNode<E> parentOfRightMost = current;
TreeNode<E> rightMost = current.left;
while(rightMost.right != null){
parentOfRightMost = rightMost;
rightMost = rightMost.right;
}
current.element = rightMost.element;
if(parentOfRightMost.right == rightMost){
parentOfRightMost.right = rightMost.left;
}else{
parentOfRightMost.left = rightMost.left;
}
balancePath(parentOfRightMost.element);
}
size--;
return true;
}
protected static class AVLTreeNode<E> extends BST.TreeNode<E>{
protected int height = 0;
public AVLTreeNode(E e){
super(e);
}
}
}Four 、 test AVLTree class
public class TestAVLTree {
public static void main(String[] args){
AVLTree<Integer> tree = new AVLTree<Integer>(new Integer[]{25, 20 ,5});
System.out.print("After inserting 25,20,,5: ");
printTree(tree);
tree.insert(34);
tree.insert(50);
System.out.print("\nAfter inserting 34, 50 : ");
printTree(tree);
tree.insert(30);
System.out.print("\nAfter inserting 30 : ");
printTree(tree);
tree.insert(10);
System.out.print("\nAfter inserting 10 : ");
printTree(tree);
tree.delete(34);
tree.delete(30);
tree.delete(50);
System.out.print("\nAfter removing 34, 30, 50: ");
printTree(tree);
tree.delete(5);
System.out.print("\nAfter removing 5 : ");
printTree(tree);
System.out.print("\nTraverse the element in the tree: ");
for(Object e : tree){
System.out.print(e + " ");
}
}
public static void printTree(BST tree){
System.out.print("\nInorder (sorted) : ");
tree.inorder();
System.out.print("\nPostorder : ");
tree.postorder();
System.out.print("\nPreorder");
tree.preorder();
System.out.print("\nThe number of nodes is " + tree.getSize());
System.out.println();
}
}Program insertion diagram :

Program delete icon :

边栏推荐
- Seata中1.5.1 是否支持mysql8?
- Returning to the top of the list, the ID is still weak
- The newly born robot dog can walk by himself after rolling for an hour. The latest achievement of Wu Enda's eldest disciple
- Hardware development notes (9): basic process of hardware development, making a USB to RS232 module (8): create asm1117-3.3v package library and associate principle graphic devices
- [target tracking] |stark
- Please, stop painting star! This has nothing to do with patriotism!
- Description | Huawei cloud store "commodity recommendation list"
- Using swiper to make mobile phone rotation map
- 综述 | 激光与视觉融合SLAM
- The last picture is seamlessly connected with the first picture in the swiper rotation picture
猜你喜欢

精益六西格玛项目辅导咨询:集中辅导和点对点辅导两种方式

Pico, can we save consumer VR?

【显存优化】深度学习显存优化方法

大龄测试/开发程序员该何去何从?是否会被时代抛弃?

七夕表白攻略:教你用自己的专业说情话,成功率100%,我只能帮你们到这里了啊~(程序员系列)

Introduction to RT thread env tool (learning notes)

MySQL的零拷贝技术
![[IDM] IDM downloader installation](/img/2b/baf8852b422c1c4a18e9c60de864e5.png)
[IDM] IDM downloader installation

一次革命、两股力量、三大环节:《工业能效提升行动计划》背后的“减碳”路线图...

ATSs: automatically select samples to eliminate the difference between anchor based and anchor free object detection methods
随机推荐
STM32F4-TFT-SPI时序逻辑分析仪调试记录
【一天学awk】函数与自定义函数
Pico,能否拯救消费级VR?
药品溯源夯实安全大堤
【显存优化】深度学习显存优化方法
Research on manually triggering automatic decision of SAP CRM organization model with ABAP code
一次革命、两股力量、三大环节:《工业能效提升行动计划》背后的“减碳”路线图...
2022 Moonriver全球黑客松优胜项目名单
Pocket network supports moonbeam and Moonriver RPC layers
【STM32学习】 基于STM32 USB存储设备的w25qxx自动判断容量检测
自动、智能、可视!深信服SSLO方案背后的八大设计
Pocket Network为Moonbeam和Moonriver RPC层提供支持
Qt+pcl Chapter 6 point cloud registration ICP series 4
ABAP-屏幕切换时,刷新上一个屏幕
Some abilities can't be learned from work. Look at this article, more than 90% of peers
新出生的机器狗,打滚1小时后自己掌握走路,吴恩达开山大弟子最新成果
[cloud trend] new wind direction in June! Cloud store hot list announced
大龄测试/开发程序员该何去何从?是否会被时代抛弃?
HR interview: the most common interview questions and technical answers
你TM到底几点下班?!!!