题目:https://pintia.cn/problem-sets/994805342720868352/problems/994805404939173888
给定一个插入序列,求一棵平衡二叉树,结果返回根结点的值,这题比较复杂,是我不会的题,重点是insert函数
几个函数列举一下
- 新建结点函数new_node(int v)
- 求树高函数get_height(node* root)
- 更新树高函数updata_height(node* root)
- 平衡因子函数get_balance_factor(node* root),忘了这个
- 左旋函数L(node* &root)
- 右旋函数R(node* &root)
- 插入函数insert(node* &root, int v)
代码
#include<algorithm>#include<vector>#include<cstdio>using namespace std;const int maxn = 30;struct Node{int data, height;Node* lchild;Node* rchild;}*root;int n;Node* new_node(int v){Node* node = new Node;node->data = v;node->height = 1;node->lchild = node->rchild = NULL;return node;}int get_height(Node* root){if(root == NULL) return 0;return root->height;}void updata_height(Node* root){root->height = max(get_height(root->lchild),get_height(root->rchild)) + 1;}int get_balance_factor(Node* root){return get_height(root->lchild) - get_height(root->rchild);}void L(Node* &root){Node* temp = root->rchild;root->rchild = temp->lchild;temp->lchild = root;updata_height(root);updata_height(temp);root = temp;}void R(Node* &root){Node* temp = root->lchild;root->lchild = temp->rchild;temp->rchild = root;updata_height(root);updata_height(temp);root = temp;}void insert(Node* &root, int v){if(root == NULL){//开始插入root = new_node(v);return;}if(v < root->data){//如果小于根结点insert(root->lchild, v);updata_height(root);if(get_balance_factor(root) == 2){if(get_balance_factor(root->lchild) == 1){R(root);} else if(get_balance_factor(root->lchild) == -1){L(root->lchild);R(root);}}} else {//如果比根结点大insert(root->rchild, v);updata_height(root);if(get_balance_factor(root) == -2){if(get_balance_factor(root->rchild) == -1){L(root);} else if(get_balance_factor(root->rchild) == 1){R(root->rchild);L(root);}}}}int main(){scanf("%d",&n);int num;for(int i = 0; i < n; i++){scanf("%d",&num);insert(root, num);}printf("%d\n", root->data);return 0;}
