平衡二叉搜尋樹的插入和先序遍歷
阿新 • • 發佈:2019-01-08
構建一個值的型別為int的平衡二叉搜尋樹,輸入N,然後進行N次插入操作,每次插入之後進行一次遍歷驗證程式碼正確性。(刪除目前還寫不出來,以後有機會再補吧)
#include "bits/stdc++.h" using namespace std; typedef long long LL; const int INF = 0x3f3f3f3f; struct AVL { int value; int height; AVL* father; AVL* lson; AVL* rson; }*root; AVL* fafa; AVL* fa; AVL* me; AVL* init(int val, AVL* fa) { AVL* point = (AVL*)malloc(sizeof(AVL)); point->value = val; point->father = fa; point->height = 1; point->lson = point->rson = NULL; return point; } void updateHeight(AVL* point) { int lheight = point->lson == NULL ? 0 : point->lson->height;int rheight = point->rson == NULL ? 0 : point->rson->height; point->height = max(lheight, rheight) + 1; if (point->father != NULL) { updateHeight(point->father); } } bool unbalance(AVL* point) { me = point; fa = point->father; fafa = fa->father;if (fafa == NULL) { return false; } int lheight = fafa->lson == NULL ? 0 : fafa->lson->height; int rheight = fafa->rson == NULL ? 0 : fafa->rson->height; if (abs(lheight - rheight) > 1) { return true; } return unbalance(fa); } void leftRotate(AVL* fa, AVL* me) { AVL* fafa = fa->father; me->father = fafa; if (fafa != NULL) { if (fafa->lson == fa) { fafa->lson = me; } else { fafa->rson = me; } } fa->rson = me->lson; if (me->lson != NULL) { me->lson->father = fa; } fa->father = me; me->lson = fa; updateHeight(fa); } void rightRotate(AVL* fa, AVL* me) { AVL* fafa = fa->father; me->father = fafa; if (fafa != NULL) { if (fafa->lson == fa) { fafa->lson = me; } else { fafa->rson = me; } } fa->lson = me->rson; if (me->rson != NULL) { me->rson->father = fa; } fa->father = me; me->rson = fa; updateHeight(fa); } void rebalance() { if (fafa->lson == fa && fa->lson == me) { rightRotate(fafa, fa); return; } if (fafa->rson == fa && fa->rson == me) { leftRotate(fafa, fa); return; } if (fafa->lson == fa && fa->rson == me) { leftRotate(fa, me); rightRotate(fafa, me); return; } rightRotate(fa, me); leftRotate(fafa, me); } void insert(int val) { AVL* father = NULL; AVL* now = root; while (now != NULL) { if (now->value == val) { return; } father = now; if (now->value < val) { now = now->rson; } else { now = now->lson; } } if (father == NULL) { root = init(val, NULL); return; } else if (father->value < val) { father->rson = init(val, father); updateHeight(father); if (unbalance(father->rson)) { rebalance(); } } else { father->lson = init(val, father); updateHeight(father); if (unbalance(father->lson)) { rebalance(); } } } void ergodic(AVL* point) { if (point == NULL) { return; } printf("%d ", point->value); ergodic(point->lson); ergodic(point->rson); } int main() { int N, value; scanf("%d", &N); while (N--) { scanf("%d", &value); insert(value); if (root->father != NULL) { root = root->father; } ergodic(root); puts(""); } return 0; }