今天想复习一下AVL树和红黑树,想写出来,没想到太难了,我太难了 :(
AVL树的左旋:左节点成为根,右节点接管原根节点,原根节点接管左节点的右节点。
只写了AVL树的插入:
template <typename T> class AVLNode { public: T value; AVLNode* left; AVLNode* right; int height; bool valid; AVLNode():value(0),left(nullptr),right(nullptr),height(0){} AVLNode(const T& v, AVLNode* l=nullptr, AVLNode* r=nullptr, int h=0,bool varg=true) :value(v), left(l), right(r), height(h),valid(varg){} }; class AVLTree { public: using EleType = int; using NodeType = AVLNode<EleType>; AVLTree(); void insert(const EleType& val); private: NodeType* _head; void insert(const EleType& val, NodeType*& cur); void leftRotate(NodeType*& k2); void rightRotate(NodeType*& k2); void rightLeftRotate(NodeType*& k3); void leftRightRotate(NodeType*& k3); void balance(NodeType*& cur); const int MAX_DIFF_HEIGHT = 1; int height(const NodeType* cur)const; }; AVLTree::AVLTree() { _head = nullptr; } void AVLTree::insert(const EleType& val) { insert(val, _head); } void AVLTree::insert(const EleType& val,NodeType*& cur) { if (_head == nullptr) { NodeType* n = new NodeType(val); _head = n; return; } if (cur == nullptr) { cur = new NodeType(val); } else if (val <= cur->value) { insert(val, cur->left); } else if (val > cur->value) { insert(val, cur->right); } balance(cur); } void AVLTree::leftRotate(NodeType*& k2) { NodeType* k1 = k2->left; k2->left = k1->right; k1->right = k2; k2->height = std::max(height(k2->left), height(k2->right)) + 1; k1->height = std::max(height(k1->left), k2->height) + 1; k2 = k1; } void AVLTree::rightRotate(NodeType*& k1) { NodeType* k2 = k1->right; k1->right = k2->left; k2->left = k1; k1 = k2; k2->height = std::max(height(k2->left), height(k2->right)) + 1; k1->height = std::max(height(k1->left), height(k1->right)) + 1; } void AVLTree::rightLeftRotate(NodeType*& k3) { rightRotate(k3->left); leftRotate(k3); } void AVLTree::leftRightRotate(NodeType*& k3) { leftRotate(k3->right); rightRotate(k3); } void AVLTree::balance(NodeType*& cur) { if (cur == nullptr) return; int lefthight = height(cur->left); int rightheight = height(cur->right); if ((lefthight-rightheight)>MAX_DIFF_HEIGHT) { if (height(cur->left->left) >= height(cur->left->right)) { leftRotate(cur); } else { rightLeftRotate(cur); } } else if ((rightheight - lefthight) > MAX_DIFF_HEIGHT) { if (height(cur->right->right) >= height(cur->right->left)) { rightRotate(cur); } else { leftRightRotate(cur); } } cur->height = std::max(lefthight, rightheight) + 1; } int AVLTree::height(const NodeType* cur) const { return cur == nullptr ? -1 : cur->height; }