zoukankan      html  css  js  c++  java
  • A1066 Root of AVL Tree [avl 插入/模板题]

    在这里插入图片描述

    #include<iostream>
    #include<vector>
    #include<queue>
    #include<stack>
    #include<string>
    #include<math.h>
    #include<algorithm>
    using namespace std;
    const int maxn = 1001;
    struct node
    {
    	int v, height;
    	node* left, * right;
    }*root;
    
    node* newnode(int v)
    {
    	node* Node = new node;
    	Node->v = v;
    	Node->height = 1;
    	Node->left = Node->right = NULL;
    	return Node;
    }
    
    int getheight(node* root)
    {
    	if (root == NULL) return 0;
    	return root->height;
    }
    
    void updataheight(node* root)
    {
    	root->height = max(getheight(root->left), getheight(root->right)) + 1;
    }
    
    int getbalancefactor(node* root)
    {
    	return getheight(root->left) - getheight(root->right);
    }
    
    void l(node* &root)
    {
    	node* temp = root->right;
    	root->right = temp->left;
    	temp->left = root;
    	updataheight(root);
    	updataheight(temp);
    	root = temp;
    }
    
    void r(node*& root)
    {
    	node* temp = root->left;
    	root->left = temp->right;
    	temp->right = root;
    	updataheight(root);
    	updataheight(temp);
    	root = temp;
    }
    
    void insert(node*& root, int v)
    {
    	if (root == NULL)
    	{
    		root = newnode(v);
    		return;
    	}
    	if (v < root->v)
    	{
    		insert(root->left, v);
    		updataheight(root);
    		if (getbalancefactor(root) == 2)
    		{
    			if (getbalancefactor(root->left) == 1)
    				r(root);
    			else if (getbalancefactor(root->left) == -1)
    			{
    				l(root->left);
    				r(root);
    			}
    		}
    	}
    	else
    	{
    		insert(root->right, v);
    		updataheight(root);
    		if (getbalancefactor(root) == -2)
    		{
    			if (getbalancefactor(root->right) == -1)
    				l(root);
    			else if (getbalancefactor(root->right) == 1)
    			{
    				r(root->right);
    				l(root);
    			}
    		}
    	}
    }
    
    int main()
    {
    	int n, v;
    	cin >> n;
    	for (int i = 0; i < n; i++)
    	{
    		cin >> v;
    		insert(root, v);
    	}
    	cout << root->v << endl;
    	return 0;
    }
    
    
  • 相关阅读:
    Linux调度器性能分析
    [ZJOI2009]假期的宿舍
    CH1601 【模板】前缀统计 (trie树)
    P2580 于是他错误的点名开始了
    P1608 路径统计
    P4779 【模板】单源最短路径
    [JLOI2014]松鼠的新家
    [NOI2015]软件包管理器
    [HAOI2015]树上操作
    P3386 【模板】二分图匹配
  • 原文地址:https://www.cnblogs.com/Hsiung123/p/13812004.html
Copyright © 2011-2022 走看看