我插入AVL_tree的实现:
void AVL_Tree::insert(const Tree & x, avl_node* & t){
//cout << "in avltree insert with 2 param" << endl;
if(t == NULL){ //empty tree or does not exist in tree
//cout << "adding new node" << endl;
avl_node* p = new avl_node(x, NULL, NULL, 0);
t = p;
++size;
cout << "added new node success" << endl;
}
else if(x < t->element){
cout << " x < t element" << endl;
insert(x, t->left);
cout << "inserted LEFT" << endl;
if((get_height(t->left))-(get_height(t->right)) == 2){ //balance factor = 2
if(x < t->left->element){ //inserted to the left subtree of the left child
LL_rotation(t);
cout << "LL rotation" << endl;
}
else{ //inserted to the right subtree of the left child
LR_rotation(t);
cout << "LR rotation" << endl;
}
}
}
else if(t->element < x){
cout << " x > t eleemtn " << endl;
insert(x, t->right);
cout << "inserted RIGHT" << endl;
if((get_height(t->right))-(get_height(t->left)) == 2){ //balance factor = 2
if(t->right->element < x){ //inserted into the right subtree of the right child
RR_rotation(t);
cout << "RR rotation" << endl;
}
else{ //inserted into the left subtree of the right child
RL_rotation(t);
cout << "RL rotation" << endl;
}
}
}
else{ //duplicate; do not need to insert into tree
cout << " duplicate? " << endl;
;
t->height = max(get_height(t->left), get_height(t->right)) + 1; //saves the height of the AVL tree after insertion
}
}
我的打印功能,用于对AVL树进行有序遍历:
void AVL_Tree::print (ostream & out, avl_node* t) const{
if(t != NULL){
print(out, t->left);
out << t->element << endl;
print(out, t->right);
}
}
我有99个节点但不知何故,当我打印时只打印了大约10个节点。我相信插入工作正常,因为树的大小是99.我在代码中遗漏了一些东西来遍历AVL进行打印吗?