1. 程式人生 > 其它 >平衡二叉樹的基本操作 (pat) 1066 Root of AVL Tree (25 分)

平衡二叉樹的基本操作 (pat) 1066 Root of AVL Tree (25 分)

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integerN(≤) which is the total number of keys to be inserted. ThenNdistinct integer keys are given in the next line. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the root of the resulting AVL tree in one line.

#include <bits/stdc++.h>
using namespace std;
int n;
struct node{
    int v,height;
    node *lchild,*rchild;
} *root;

node* newNode(int v){
    node *Node = new node;//申請一個新的地址空間 
    Node->v = v;
    Node->height = 1
; Node->lchild = Node->rchild = NULL; return Node; } //返回以root為根節點的子樹當前的height int getHeight(node *root){ if(root == NULL) return 0; return root->height; } //更新節點root的heifht //由於在涉及到相應的AVL樹進行相應的調整時,只有部分節點的高度發生了相應的變化,所以在進行調整時 //直接呼叫每個節點對應的height進行相應的更新,而不需要遞迴進行更新 void updateHeight(node* root){
//left和right中max進行相應的更新 root->height = max(getHeight(root->lchild),getHeight(root->rchild))+1; } int getBalanceFactor(node* root){ return getHeight(root->lchild)-getHeight(root->rchild); } //對AVL樹調整的兩個關鍵操作 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; } void insert(node *&root,int v){ //進行插入 if(root == NULL){ root = newNode(v); return; } if(v < root->v){ //由於插入的是左子樹,所以只能導致L形開頭 insert(root->lchild,v); 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,v); 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); } } } } int main(){ int n; cin>>n; int tmp; node* root = NULL; for(int i=0;i<n;i++){ cin>>tmp; insert(root,tmp); } cout<<root->v<<endl; return 0; }