果然我还是太弱了。。。这道题花了我大约5个钟头,看了各种资料,来实现一颗自平衡的搜索树
推荐大家看这个,如何一步一步写平衡二叉树
http://www.cppblog.com/cxiaojia/archive/2013/07/22/187776.html
平衡二叉树的难点在于插入以后,如何调整,如何计算树的高度等等等等
而递归用来解决这种问题是很简单的(一点也不简单)
#include <iostream> using namespace std; typedef struct treeNode{ int data; struct treeNode* leftSon; struct treeNode* rightSon; int height; }treeNode; int max(int a, int b) { if (a > b){ return a; } else{ return b; } } int GetHeight(treeNode *root) { if (root == NULL){ return 0; } else return root->height; } treeNode* RotatingL(treeNode *root) { treeNode* K2 = root; treeNode* K1 = root->leftSon; K2->leftSon = K1->rightSon; K1->rightSon = K2; K2->height = max(GetHeight(K2->leftSon), GetHeight(K2->rightSon)) + 1; K1->height = max(GetHeight(K1->leftSon), GetHeight(K1->rightSon)) + 1; return K1; } treeNode* RotatingR(treeNode *root) { treeNode* K2 = root; treeNode* K1 = root->rightSon; K2->rightSon = K1->leftSon; K1->leftSon = K2; K2->height = max(GetHeight(K2->leftSon), GetHeight(K2->rightSon)) + 1; K1->height = max(GetHeight(K1->leftSon), GetHeight(K1->rightSon)) + 1; return K1; } treeNode* RotatingLR(treeNode *root) { root->leftSon = RotatingR(root->leftSon); return RotatingL(root); } treeNode* RotatingRL(treeNode *root) { root->rightSon = RotatingL(root->rightSon); return RotatingR(root); } treeNode* insert(treeNode* root, int value) { if (root == NULL){ root = (treeNode *)malloc(sizeof(treeNode)); root->data = value; root->leftSon = root->rightSon = NULL; } else if (value < root->data){ root->leftSon = insert(root->leftSon, value); if (GetHeight(root->leftSon) - GetHeight(root->rightSon) == 2){ if (value < root->leftSon->data){ root = RotatingL(root); } else{ root = RotatingLR(root); } } } else { root->rightSon = insert(root->rightSon, value); if (GetHeight(root->rightSon) - GetHeight(root->leftSon) == 2){ if (value > root->rightSon->data){ root = RotatingR(root); } else{ root = RotatingRL(root); } } } root->height = max(GetHeight(root->leftSon), GetHeight(root->rightSon)) + 1; return root; } int main() { int n; cin >> n; treeNode* root = NULL; for (int i = 0; i < n; i++){ int t; cin >> t; root = insert(root, t); } cout << root->data; }
时间: 2024-10-19 16:00:05