【PAT】A1066 Root of AVL Tree (25分)

tech2022-07-15  170

题目

解决

思路

正常建立一棵AVL树

实现

Code1

#include<cstdio> #include<algorithm> using namespace std; const int maxn = 25; struct node{ int data; int height; node* lchild; node* rchild; }; node* newNode(int x){ node* Node = new node; Node->data = x; Node->height = 1; Node->lchild = Node->rchild = NULL; return Node; } int getHeight(node* root){ if(root == NULL) return 0; return root->height; } void updateHeight(node* root){ root->height = max(getHeight(root->lchild), getHeight(root->rchild)) + 1; } void L(node* &root){ node* temp = root->rchild; root->rchild = temp->lchild; temp->lchild = root; updateHeight(root); updateHeight(temp); root = temp; } void R(node* &root){ node* temp = root->lchild; root->lchild = temp->rchild; temp->rchild = root; updateHeight(root); updateHeight(temp); root = temp; } int getBalanceFactor(node* root){ return getHeight(root->lchild) - getHeight(root->rchild); } void insert(node* &root, int x){ if(root == NULL){ root = newNode(x); return; } if(x < root->data){ insert(root->lchild, x); updateHeight(root); if(getBalanceFactor(root) == 2){ if(getBalanceFactor(root->lchild) == 1){ //LL R(root); }else if(getBalanceFactor(root->lchild) == -1){ //LR L(root->lchild); R(root); } } }else{ insert(root->rchild, x); updateHeight(root); if(getBalanceFactor(root) == -2){ if(getBalanceFactor(root->rchild) == -1){ //RR L(root); }else if(getBalanceFactor(root->rchild) == 1){ //RL R(root->rchild); L(root); } } } } node* create(int data[], int n){ node* root = NULL; for(int i=0; i<n; i++){ insert(root, data[i]); } return root; } int main(){ int n; scanf("%d", &n); int data[maxn]; for(int i=0; i<n; i++){ scanf("%d", &data[i]); } node* root = create(data, n); printf("%d", root->data); return 0; }
最新回复(0)