1066.Root of AVL Tree

【题意】
        给出一个AVL树的添加节点顺序,输出最后得到的树的根对应的值

【思路】

        直接模拟即可,纯属考察概念


#include <iostream>
#include <algorithm>
using namespace std;

typedef struct node{
	int value;
	node *left;
	node *right;
	node(int v):value(v),left(NULL),right(NULL){};
	node():left(NULL),right(NULL){};
}BiNode;

int getHeight(BiNode *T){
	if(T==NULL){
		return 0;
	}
	return max(getHeight(T->left),getHeight(T->right))+1;
}

bool isBalanced(BiNode *T){
	int lHeight,rHeight;

	lHeight = getHeight(T->left);
	rHeight = getHeight(T->right);
	
	return abs(lHeight-rHeight)<=1;
}

BiNode *LL(BiNode *a){
	BiNode *b;

	b = a->left;
	a->left = b->right;
	b->right = a;

	return b;
}

BiNode *RR(BiNode *a){
	BiNode *b;

	b = a->right;
	a->right = b->left;
	b->left = a;

	return b;
}

BiNode *LR(BiNode *a){
	a->left = RR(a->left);
	return LL(a);
}

BiNode *RL(BiNode *a){
	a->right = LL(a->right);
	return RR(a);
}

BiNode *insertNode(BiNode *root, int num){
	if(root==NULL){
		root = new BiNode(num);
		return root;
	}
	else if(num<root->value){
		root->left = insertNode(root->left, num);
		if(!isBalanced(root)){
			//LL
			if(num<root->left->value){
				root = LL(root);
			}
			//LR
			else{
				root = LR(root);
			}
		}
	}
	else{
		root->right = insertNode(root->right, num);
		if(!isBalanced(root)){
			//RL
			if(num<root->right->value){
				root = RL(root);
			}
			//RR
			else{
				root = RR(root);
			}
		}
	}

	return root;
}

int main(){
	int n;
	BiNode *head = NULL;

	cin >> n;

	for(int i=0; i<n; i++){
		int num;
		cin >> num;
		head = insertNode(head, num);
	}

	cout << head->value;

	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值