数据结构与算法分析——c语言描述 练习4.43b 答案
看了作者给的思路写出来。复杂度不会证。证明也看不懂。。。。。。。。。。。。。。
日后我会重新把这本书的所有复杂度证明刷一编的。
头文件包括的二叉树的代码。
#include<stdlib.h>
#include"tree.h"
#include<stdio.h>
struct TreeNode {
ElementType element;
SearchTree left;
SearchTree right;
};
Position singleRotateWithLeft(Position k2) {
Position k1 = k2->left;
Position y = k1->right;
k2->left = y;
k1->right = k2;
return k1;
}
Position singleRotateWithRight(Position k1) {
Position k2 = k1->right;
Position y = k2->left;
k1->right = y;
k2->left = k1;
return k2;
}
SearchTree rotateToRoot(SearchTree t, ElementType X) {
if (X < t->element) {
t->left=rotateToRoot(t->left, X);
return singleRotateWithLeft(t);
}
else if (X > t->element) {
t->right= rotateToRoot(t->right, X);
return singleRotateWithRight(t);
}
else {
return t;
}
}
SearchTree rotateTwoSearchTreeToSame(SearchTree t1,SearchTree t2) {
if (t1&&t2) {
t1 = rotateToRoot(t1, t2->element);
t1->left =rotateTwoSearchTreeToSame(t1->left, t2->left);
t1->right= rotateTwoSearchTreeToSame(t1->right, t2->right);
return t1;
}
return NULL;
}
void Dir(SearchTree t) {
if (t) {
printf("%d ", t->element);
Dir(t->left);
Dir(t->right);
}
}
int main() {
int randInt[49];
for (int i = 0; i < 49; i++)
randInt[i] = rand();
SearchTree t1 = NULL;
SearchTree t2 = NULL;
for (int i = 48; i >= 0; i--)
t1 = insert(randInt[i], t1);
for (int i = 0; i <49; i++)
t2 = insert(randInt[i], t2);
t1= rotateTwoSearchTreeToSame(t1, t2);
Dir(t1);
printf("\n");
printf("\n");
printf("\n");
printf("\n");
Dir(t2);
}