1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
| #include <bits/stdc++.h> using namespace std; template <typename T> struct TreeNode { TreeNode* left; TreeNode* right; T data; int height; }; template <typename T> class AVLTree { public: TreeNode<T>* root; AVLTree() : root(nullptr) {}
void leftRotate(TreeNode<T>*& k2) { TreeNode<T>* k1 = k2->right; k2->right = k1->left; k1->left = k2; k2->height = max(height(k2->left), height(k2->right)) + 1; k1->height = max(k2->height, height(k1->right)) + 1; k2 = k1; }
void rightRotate(TreeNode<T>*& k2) { TreeNode<T>* k1 = k2->left; k2->left = k1->right; k1->right = k2; k2->height = max(height(k2->left), height(k2->right)) + 1; k1->height = max(height(k1->left), k2->height) + 1; k2 = k1; }
void leftRightRotate(TreeNode<T>*& k3) { leftRotate(k3->left); rightRotate(k3); }
void rightLeftRotate(TreeNode<T>*& k3) { rightRotate(k3->right); leftRotate(k3); }
int height(TreeNode<T>* t) const { return t == nullptr ? -1 : t->height; }
void balance(TreeNode<T>*& t) { if (t == nullptr) { return; } else if (height(t->left) - height(t->right) > 1) { if (height(t->left->left) >= height(t->left->right)) { rightRotate(t); } else { leftRightRotate(t); } } else if (height(t->right) - height(t->left) > 1) { if (height(t->right->right) >= height(t->right->left)) { leftRotate(t); } else { rightLeftRotate(t); } } t->height = max(height(t->left), height(t->right)) + 1; }
void insertImpl(T& data, TreeNode<T>*& t) { if (!t) { t = new TreeNode<T>; t->data = data; t->left = t->right = nullptr; } else if (data >= t->data) { insertImpl(data, t->right); } else if (data <= t->data) { insertImpl(data, t->left); } balance(t); }
void insert(T& data) { insertImpl(data, root); }
void BFS() { if (!root) return; queue<tuple<TreeNode<T>*, int, bool>> q; q.push({root, 0, false}); int l = 0; while (q.size()) { auto [v, h, isNull] = q.front(); q.pop(); if (h != l) { cout << endl; l = h; } if (!isNull) cout << v->data << " "; else cout << "nil "; if (v && v->left) q.push({v->left, h + 1, false}); else if (v) q.push({nullptr, h + 1, true}); if (v && v->right) q.push({v->right, h + 1, false}); else if (v) q.push({nullptr, h + 1, true}); } cout << endl; } };
int main() { vector<int> arr; for (int i = 0; i < 5; i++) arr.push_back(i); AVLTree<int> tr; for (int i : arr) { tr.insert(i); } tr.BFS(); return 0; }
|