写出执行双旋转的函数,其效率要超过执行两个单旋转

数据结构与算法分析——c语言描述 练习4.22  答案


就是人工展开两个单旋转的函数。画个图就行了。


static Position doubleRotateWithLeft(Position k3) {
	Position k1 = k3->left;
	Position k2 = k1->right;
	k1->right = k2->left;
	k3->left = k2->right;
	k2->left = k1;
	k2->right = k3;
	k1->height = Max(height(k1->left), height(k1->right)) + 1;
	k3->height = Max(height(k3->left), height(k3->right)) + 1;
	k2->height = Max(height(k2->left), height(k2->right)) + 1;
	return k2;
}



static Position doubleRotateWithRight(Position k1) {
	Position k3 = k1->right;
	Position k2 = k3->left;
	k1->right = k2->left;
	k3->left = k2->right;
	k2->left = k1;
	k2->right = k3;
	k1->height = Max(height(k1->left), height(k1->right)) + 1;
	k3->height = Max(height(k3->left), height(k3->right)) + 1;
	k2->height = Max(height(k2->left), height(k2->right)) + 1;
	return k2;
}


你可能感兴趣的:(写出执行双旋转的函数,其效率要超过执行两个单旋转)