平衡二叉樹建立
阿新 • • 發佈:2019-02-12
Time Limit: 400 ms Memory Limit: 65536 KiB
#include <stdio.h> #include <stdlib.h> #include <string.h> struct node { int data; int high; struct node *lt, *rt; }; int max(int a, int b) { return a>b?a:b; } ///深度 int deep(struct node *root) { if(root==NULL) return -1; else return root->high; } struct node *LL(struct node *root) { struct node *p=root->lt; root->lt=p->rt; p->rt=root; root->high=max(deep(root->lt), deep(root->rt))+1; return p; } struct node *RR(struct node *root) { struct node *p=root->rt; root->rt=p->lt; p->lt=root; root->high=max(deep(root->lt), deep(root->rt))+1; return p; } struct node *RL(struct node *root) { root->rt=LL(root->rt); root=RR(root); return root; } struct node *LR(struct node *root) { root->lt=RR(root->lt); root=LL(root); return root; } struct node *Insert(struct node *root, int num) { if(!root) { root=(struct node *)malloc(sizeof(struct node)); root->data=num; root->high=0; root->lt=NULL; root->rt=NULL; } else { if(num<root->data)///資料比根小 { root->lt=Insert(root->lt, num);///加到左子樹上 ///先判斷是否要轉 if(abs(deep(root->lt)-deep(root->rt))>1)//深度之差大於一就轉 { if(num>=root->lt->data)///比左子根大,轉兩次,即LR { root=LR(root); } else ///比左子根小,轉一次,即LL { root=LL(root); } } } else///比根大 { root->rt=Insert(root->rt, num);///加到右子樹上 if(abs(deep(root->lt)-deep(root->rt))>1) { if(num>=root->rt->data)///加到右子樹的右邊,轉一次,RR { root=RR(root); } else///加到右子樹的左邊,轉兩次,RL { root=RL(root); } } } } root->high=max(deep(root->lt), deep(root->rt))+1; return root; } int main() { struct node *root=NULL; int n, num; scanf("%d", &n); while(n--) { scanf("%d", &num); root=Insert(root, num); } printf("%d\n", root->data); return 0; }