#include<stdio.h> #include<stdlib.h> #define INFO 0x3ff #define NEINFO -0x3ff typedef enum ColorType{ Black,Red }ColorType; struct Node{ int data; ColorType Colory; struct Node *Left,*Right; }; typedef struct Node* RedBlackTree; typedef RedBlackTree Position; Position NUllNode = NULL; RedBlackTree Init() { RedBlackTree T; if(NUllNode==NULL) { NUllNode=(RedBlackTree)malloc(sizeof(struct Node)); if(NUllNode==NULL) printf("Out of Space!!!"); NUllNode->Left=NUllNode->Right=NUllNode; NUllNode->data=INFO; NUllNode->Colory=Black; } T=(RedBlackTree)malloc(sizeof(struct Node)); if(T==NULL) printf("Out of Space!!!"); T->Left=T->Right=NUllNode; T->data=NEINFO; T->Colory=Black; return T; } RedBlackTree SingleLeftRotate(RedBlackTree T) { RedBlackTree p=T->Left; T->Left=p->Right; p->Right=T; return p; } RedBlackTree SingleRightRotate(RedBlackTree T) { RedBlackTree p=T->Right; T->Right=p->Left; p->Left=T; return p; } RedBlackTree Rotate(int Item,RedBlackTree T) { if(Item<T->data) { return T->Left=(Item<T->Left->data? SingleLeftRotate(T->Left): SingleRightRotate(T->Left)); } else { return T->Right=(Item>T->Right->data? SingleRightRotate(T->Right): SingleLeftRotate(T->Right)); } } static RedBlackTree X,P,GP,GPP; static void HandleReorient(int Item,RedBlackTree T) { X->Colory=Red; X->Left->Colory=Black; X->Right->Colory=Black; if(P->Colory==Red) { X->Colory=Black; if((Item<GP->data)!=(Item<P->data)) P=Rotate(Item,GP); X=Rotate(Item,GPP); X->Colory=Black; } T->Right->Colory=Black; } RedBlackTree Insert(int Item,RedBlackTree T) { X=P=GP=T; NUllNode->data=Item; while(Item!=X->data) { GPP=GP;GP=P;P=X; if(Item<X->data) { X=X->Left; } else { X=X->Right; } if(X->Left->Colory==Red&&X->Right->Colory==Red) HandleReorient(Item,T); } if(X!=NUllNode) return NUllNode; X=(RedBlackTree)malloc(sizeof(struct Node)); if(X==NULL) printf("Out of Space!!!"); X->Left=X->Right=NUllNode; X->data=Item; if(Item<P->data) P->Left=X; else P->Right=X; HandleReorient(Item,T); return T; } void PrePrint(RedBlackTree T) { if(T!=NUllNode) { printf("%d ",T->data); PrePrint(T->Left); PrePrint(T->Right); } } int main(void) { RedBlackTree T=Init(); int n,i,x; scanf("%d",&n); for(i=0;i<n;i++) { scanf("%d",&x); T=Insert(x,T); //printf("-11"); } PrePrint(T->Right); return 0; }