zoukankan      html  css  js  c++  java
  • PAT甲级1066. Root of AVL Tree

    PAT甲级1066. Root of AVL Tree

    题意:

    构造AVL树,返回root点val。

    思路:

    了解AVL树的基本性质。
    AVL树

    ac代码:

    C++

    // pat1066.cpp : 定义控制台应用程序的入口点。
    //
    
    #include "stdafx.h"
    
    #include<iostream>
    #include<cstdio>
    #include<string>
    #include<algorithm>
    #include<queue>
    #include<vector>
    #include<cstring>
    #include<stdio.h>
    #include<map>
    #include<cmath>
    #include<unordered_map>
    
    using namespace std;
    
    struct AvlNode
    {
    	int data;
    	AvlNode* left;
    	AvlNode* right;
    	int height;
    	AvlNode(int x) : data(x), left(NULL), right(NULL), height(0) {}
    };
    
    int height(AvlNode* root)
    {
    	return root == NULL ? -1 : root->height;
    }
    
    void LLRotate(AvlNode*& root)        //右单
    {
    	AvlNode* temp = root->left;
    	root->left = temp->right;
    	temp->right = root;
    
    	temp->height = max(height(temp->left), height(temp->right)) + 1;
    	root->height = max(height(root->left), height(root->right)) + 1;
    
    	root = temp;
    }
    
    void RRRotate(AvlNode*& root)          //左单
    {
    	AvlNode* temp = root->right;
    	root->right = temp->left;
    	temp->left = root;
    
    	temp->height = max(height(temp->left), height(temp->right)) + 1;
    	root->height = max(height(root->left), height(root->right)) + 1;
    
    	root = temp;
    }
    
    void RLRotate(AvlNode*& root)
    {
    	LLRotate(root->right);
    
    	RRRotate(root);
    }
    
    void LRRotate(AvlNode*& root)
    {
    	RRRotate(root->left);
    
    	LLRotate(root);
    }
    
    void insert(const int& x, AvlNode*& root)
    {
    	if (!root)
    	{
    		root = new AvlNode(x);
    	}
    	else if (x < root->data)
    	{
    		insert(x, root->left);
    		if (height(root->left) - height(root->right) == 2)
    		{
    			if (x < root->left->data) LLRotate(root);
    			else LRRotate(root);
    		}
    	}
    	else if (x > root->data)
    	{
    		insert(x, root->right);
    		if (height(root->right) - height(root->left) == 2)
    		{
    			if (x > root->right->data) RRRotate(root);
    			else RLRotate(root);
    		}
    	}
    
    	root->height = max(height(root->left), height(root->right)) + 1;
    }
    
    int main()
    {
    	AvlNode* root = NULL;
    	int N;
    	int i;
    	int num[22];
    
    	scanf("%d", &N);
    
    	for (int i = 0; i < N; i++)
    	{
    		scanf("%d", &(num[i]));
    	}
    
    	for (int i = 0; i < N; i++)
    	{
    		insert(num[i], root);
    	}
    
    	printf("%d", root->data);
        return 0;
    }
    
  • 相关阅读:
    Chino 操作系统开发日志 (1)
    将Asp.Net Core和corefx移植到.Net 4.0
    C++编写操作系统(1):基于 EFI 的 Bootloader
    第二次作业:支付宝手机软件分析
    第一次作业:以人为鉴 可以明得失
    个人附加作业
    个人作业3---个人总结
    结对编程2---单元测试
    个人作业2---必应词典案例分析
    结对编程作业1
  • 原文地址:https://www.cnblogs.com/weedboy/p/7290595.html
Copyright © 2011-2022 走看看