Insert adjustment of balanced binary tree (C language)

Insert adjustment of balanced binary tree (C language)

Insertion and adjustment of balanced binary tree

Single spin left and right

Tree rotation

Single spin left and right

avltree Lrotation(avltree A) {
    
      /*左单旋*/
	avltree B = A->left;
	A->left = B->right;
	B->right = A;
	A->height = getheight(A);
	B->height = getheight(B);
	return B;
}
avltree Rrotation(avltree A) {
    
      /*右单旋*/
	avltree B = A->right;
	A->right = B->left;
	B->left = A;
	A->height = getheight(A);
	B->height = getheight(B);
	return B;
}
avltree LRrotation(avltree A) {
    
       /*左右单旋*/
	A->left = Rrotation(A->left);
	return Lrotation(A);
}
avltree RLrotation(avltree A) {
    
    
	A->right = Lrotation(A->right);
	return Rrotation(A);
}

Balanced Binary Tree Insertion

After insertion, recursively pop out of the stack, and the binary tree from the insertion point upwards to determine whether the node is balanced. The
key point is to determine which subtree of the unbalanced point is inserted in the insertion number to determine which rotation function to use, so the child node with the unbalanced point is required Compare again

avltree insert(avltree t, int num) {
    
    
	if (!t) {
    
    
		t = (avltree)malloc(sizeof(struct treenode));
		t->data = num;
		t->left = NULL;
		t->right = NULL;
		t->height = 0;
	}   /*叶节点高为0*/
	else {
    
    
		if (num < t->data) {
    
     
			t->left = insert(t->left, num); 
			if (getheight(t->left) - getheight(t->right) == 2)
			{
    
    
				if (num < t->left->data) t = Lrotation(t);  /*插入左子树的左子树左单旋*/
				else t = LRrotation(t);
			}
		}  /*左子树插入并调整平衡*/
		else if (num > t->data) {
    
     
			t->right = insert(t->right, num);
			if (getheight(t->right) - getheight(t->left) == 2)
			{
    
    
				if (num > t->right->data) t = Rrotation(t); /*插入右子树的右子树左单旋*/
				else t = RLrotation(t);
			}
		}/*右子树插入并调整平衡*/
	}
	t->height = getheight(t);/*更新树高*/
	return t;
}

Find tree height function

The default leaf node height is 0

typedef struct treenode *avltree;
struct treenode {
    
    
	avltree left;
	avltree right;
	int data;
	int height;
};
int max(int a, int b) {
    
    
	return (a > b ? a : b);
}
int getheight(avltree t) {
    
         /*求树高*/
	if (!t) return -1;
	else {
    
    
		int lheight = getheight(t->left);
		int rheight = getheight(t->right);
		return max(lheight, rheight) + 1;
	}
}

Guess you like

Origin blog.csdn.net/qq_40602655/article/details/106594116