struct AVLNode {
int depth;
AVLNode* left;
AVLNode* right;
int val;
AVLNode(int val=0) {
depth = 0;
left = right = nullptr;
this->val = val;
}
};
class AVLTree {
typedef AVLNode Node;
typedef AVLNode *PNode;
const int DEPTH_DIFFERENCE_LIMIT = 1;
public:
bool insert(const int val, PNode &n) {
if (nullptr == n) {
n = new Node(val);
balance(n);
return true;
}
else if (val < n->val) {
bool isSucc = insert(val, n->left);
balance(n);
return isSucc;
}
else if (val > n->val) {
bool isSucc = insert(val, n->right);
balance(n);
return isSucc;
}
else
return false;
}
int get_depth(PNode node) {
if (node == nullptr) {
return 0;
}
return node->depth;
}
void update_depth(PNode node) {
if (node == nullptr) {
return;
}
update_depth(node->left);
update_depth(node->right);
int l_depth = get_depth(node->left);
int r_depth = get_depth(node->right);
node->depth = max(l_depth, r_depth) + 1;
}
int get_balance(PNode n) {
if (n == nullptr) {
return 0;
}
return get_depth(n->left) - get_depth(n->right);
}
void l_rotate(PNode &n) {
auto r = n->right;
n->right = r->left;
r->left = n;
n = r;
}
void r_rotate(PNode &n) {
auto l = n->left;
n->left = l->right;
l->right = n;
n = l;
}
void rl_rotate(PNode &n) {
r_rotate(n->right);
l_rotate(n);
}
void lr_rotate(PNode &n) {
l_rotate(n->left);
r_rotate(n->right);
}
void balance(PNode &n) {
if (nullptr == n) {
return;
}
if ((get_depth(n->left) - get_depth(n->right)) > DEPTH_DIFFERENCE_LIMIT) {
if (get_depth(n->left->left) >= get_depth(n->left->right)) {
r_rotate(n);
} else {
lr_rotate(n);
}
} else if ((get_depth(n->right) - get_depth(n->left)) > DEPTH_DIFFERENCE_LIMIT) {
if (get_depth(n->right->right) >= get_depth(n->right->left)) {
l_rotate(n);
} else {
rl_rotate(n);
}
}
update_depth(n);
}
PNode getRoot() {
return root;
}
private:
PNode root = nullptr;
};
节点高度更新的代码调用还有点问题
|