#include<iostream>
#include<string.h>
#include <algorithm>
#include <string>
#include <string.h>
#include <set>
#include <vector>
#include <queue>
using namespace std;
typedef struct Node
{
int val;
Node *l,*r;
int dep;
}Node;
int n;
int shendu(Node *T)
{
if(!T) return -1;
return T->dep;
}
Node * zuozuo(Node *T)
{
Node *p = T->l;
T->l = p->r;
p->r = T;
p->dep = max(T->dep,shendu(p->l)) +1 ;
T->dep = max(shendu(T->l),shendu(T->r)) + 1;
return p;
}
Node * youyou(Node *T)
{
Node *p = T->r;
T->r = p->l;
p->l = T;
p->dep = max(T->dep,shendu(p->r)) + 1;
T->dep = max(shendu(T->l),shendu(T->r)) + 1;
return p;
}
Node *zuoyou(Node *T)
{
T->l = youyou(T->l);
return zuozuo(T);
}
Node *youzuo(Node *T)
{
T->r = zuozuo(T->r);
return youyou(T);
}
Node *Create(Node *T,int x)
{
if(!T)
{
T = (Node *)malloc(sizeof(Node));
T->l = T->r = NULL;
T->val = x;
T->dep = 0;
}
else if(x > T->val)
{
T->r = Create(T->r,x);
if(shendu(T->r) - shendu(T->l) > 1)
{
if(x > (T->r)->val)
T = youyou(T);
else
T = youzuo(T);
}
}
else if(x < T->val)
{
T->l = Create(T->l,x);
if(shendu(T->l) - shendu(T->r) > 1)
{
if(x < (T->l)->val)
T = zuozuo(T);
else
T = zuoyou(T);
}
}
T->dep = max(shendu(T->l),shendu(T->r)) + 1;
return T;
}
int main()
{
// freopen("in.txt","r",stdin);
cin >> n;
Node *T = NULL;
for(int i=0; i<n; ++i)
{
int t;
cin >> t;
T = Create(T,t);
}
cout << T->val<<endl;
return 0;
}
平衡二叉树的构建
原文作者:平衡二叉树
原文地址: https://blog.csdn.net/qq_33204081/article/details/79679033
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
原文地址: https://blog.csdn.net/qq_33204081/article/details/79679033
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。