zoukankan      html  css  js  c++  java
  • 1066. Root of AVL Tree (25)

    距离PAT考试还有 11天最重要的是做透每一题

    (1)思路

    就是考察基本的AVL树

    这里主要写的是单旋转左旋和右旋 

    双旋转可以用其组合得到

    这里要注意的是,insert,roatewithleftchild和roatewithrightchild函数都是传的引用,root初始化为0,表示插入的位置到了

    所以root的值会不断改变为当前树的根

    按照这个思路必须将left,right数组初始为零

    顺便为了好看,可以规定height[0]为-1

    #include <cstdio>
    #include <vector>
    #include <cstring>
    #include <algorithm>
    using namespace std;
    
    int n;
    int num=0;
    const int N=30;
    int a[N];
    int left[N];
    int right[N];
    int height[N];
    
    int newnode(int x) {
      num++;
      a[num]=x;
      left[num]=0;
      right[num]=0;
      height[num]=0;
      return num;
    }
    
    void roatewithleftchild(int& p) {
      int q=left[p];
      left[p]=right[q];
      right[q]=p;
      height[p]=max(height[left[p]],height[right[p]])+1;
      height[q]=max(height[left[q]],height[p]);
      p=q;
    }
    
    void roatewithrightchild(int& p) {
      int q=right[p];
      right[p]=left[q];
      left[q]=p;
      height[p]=max(height[left[p]],height[right[p]])+1;
      height[q]=max(height[right[q]],height[p]);
      p=q;
    }
    
    void insert(int x,int& p) {
      if(!p) p=newnode(x);
      else if(x < a[p]){
        insert(x,left[p]);
        // 
        if(height[left[p]] - height[right[p]] == 2) {
          if(x < a[left[p]]) roatewithleftchild(p);
          else {
        roatewithrightchild(left[p]);
        roatewithleftchild(p);
          }
        }
      } else if(x > a[p]) {
        insert(x,right[p]); 
        if(height[right[p]] - height[left[p]] == 2) {
          if(x > a[right[p]]) roatewithrightchild(p);
          else {//left-right roate
        roatewithleftchild(right[p]);
        roatewithrightchild(p);
          }
        }
      }
      height[p]=max(height[left[p]],height[right[p]])+1;
    }
    
    int main() {
      scanf("%d",&n);
      memset(a,0,sizeof(a));
      memset(left,0,sizeof(left));
      memset(right,0,sizeof(right));
      memset(height,-1,sizeof(height));
      int root=0;
      for(int i=0;i<n;i++) {
        int v;
        scanf("%d",&v);
        insert(v,root);
      }
      printf("%d
    ",a[root]);
      return 0;
    }

  • 相关阅读:
    rest framework 之前
    python之psutil
    可持久化并查集总结
    复数学习
    主席树总结
    点分治题单(来自XZY)
    Tarjan&2-SAT 总结
    AC自动机题单
    网络流题目详讲+题单(入门版)(持续更新中......)
    网络流题目详讲+题单(提高版)(持续更新中......)
  • 原文地址:https://www.cnblogs.com/tclan126/p/8525506.html
Copyright © 2011-2022 走看看