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;
    }
    
    
  • 相关阅读:
    任务墙(6月3日)
    燃尽图(6月3日)
    6.1-6.2小结
    5月28日任务进展
    个人感悟
    代码评审
    如何用ZBrush确定头部五官的位置
    ZBrush中的纹理-水手该怎样进行绘制
    怎样对ZBrush中的材料进行渲染和着色
    快速熟悉Zbrush中的四种裁切笔刷
  • 原文地址:https://www.cnblogs.com/Hsiung123/p/13812004.html
Copyright © 2011-2022 走看看