题目:https://pintia.cn/problem-sets/994805342720868352/problems/994805404939173888

给定一个插入序列,求一棵平衡二叉树,结果返回根结点的值,这题比较复杂,是我不会的题,重点是insert函数
几个函数列举一下

  1. 新建结点函数new_node(int v)
  2. 求树高函数get_height(node* root)
  3. 更新树高函数updata_height(node* root)
  4. 平衡因子函数get_balance_factor(node* root),忘了这个
  5. 左旋函数L(node* &root)
  6. 右旋函数R(node* &root)
  7. 插入函数insert(node* &root, int v)

代码

  1. #include<algorithm>
  2. #include<vector>
  3. #include<cstdio>
  4. using namespace std;
  5. const int maxn = 30;
  6. struct Node{
  7. int data, height;
  8. Node* lchild;
  9. Node* rchild;
  10. }*root;
  11. int n;
  12. Node* new_node(int v){
  13. Node* node = new Node;
  14. node->data = v;
  15. node->height = 1;
  16. node->lchild = node->rchild = NULL;
  17. return node;
  18. }
  19. int get_height(Node* root){
  20. if(root == NULL) return 0;
  21. return root->height;
  22. }
  23. void updata_height(Node* root){
  24. root->height = max(get_height(root->lchild),get_height(root->rchild)) + 1;
  25. }
  26. int get_balance_factor(Node* root){
  27. return get_height(root->lchild) - get_height(root->rchild);
  28. }
  29. void L(Node* &root){
  30. Node* temp = root->rchild;
  31. root->rchild = temp->lchild;
  32. temp->lchild = root;
  33. updata_height(root);
  34. updata_height(temp);
  35. root = temp;
  36. }
  37. void R(Node* &root){
  38. Node* temp = root->lchild;
  39. root->lchild = temp->rchild;
  40. temp->rchild = root;
  41. updata_height(root);
  42. updata_height(temp);
  43. root = temp;
  44. }
  45. void insert(Node* &root, int v){
  46. if(root == NULL){//开始插入
  47. root = new_node(v);
  48. return;
  49. }
  50. if(v < root->data){//如果小于根结点
  51. insert(root->lchild, v);
  52. updata_height(root);
  53. if(get_balance_factor(root) == 2){
  54. if(get_balance_factor(root->lchild) == 1){
  55. R(root);
  56. } else if(get_balance_factor(root->lchild) == -1){
  57. L(root->lchild);
  58. R(root);
  59. }
  60. }
  61. } else {//如果比根结点大
  62. insert(root->rchild, v);
  63. updata_height(root);
  64. if(get_balance_factor(root) == -2){
  65. if(get_balance_factor(root->rchild) == -1){
  66. L(root);
  67. } else if(get_balance_factor(root->rchild) == 1){
  68. R(root->rchild);
  69. L(root);
  70. }
  71. }
  72. }
  73. }
  74. int main(){
  75. scanf("%d",&n);
  76. int num;
  77. for(int i = 0; i < n; i++){
  78. scanf("%d",&num);
  79. insert(root, num);
  80. }
  81. printf("%d\n", root->data);
  82. return 0;
  83. }