zoukankan      html  css  js  c++  java
  • A1123 Is It a Complete AVL Tree [avl]

    在这里插入图片描述
    考察知识:avl树建树,判断一棵树是否是完全二叉树,层序遍历输出
    白痴bug卡了40分钟!!!!!

    #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;
    }
    
    
  • 相关阅读:
    图片压缩ShareSDK的简化压缩和使用例子
    qml 调试
    BSP 算法
    粒子系统(Particle System)
    QML Item Element
    Chapter 13. Playing God: Basic Physics Modeling (Tricks.of.the.Windows.Game.Programming.Gurus,.Second.Edition)
    qml资料
    wpf教程
    凸包
    QML Animation
  • 原文地址:https://www.cnblogs.com/Hsiung123/p/13812003.html
Copyright © 2011-2022 走看看