AVL дерево не может вычислить высоту дерева

Я новичок в программировании, так что этот вопрос, кажется, нуби. Извините за это, если бы это было. Итак, вот моя реализация дерева AVL, здесь я полагаю, что функции вставки и удаления работают нормально, но getheight дает мне 0 в любом случае.

#include <iostream>
using namespace std;

class node{
private:
int key;
node(int k) {key=k; left=right=0; height=1;}
int data;
int height;
node* left;
node* right;
public:
int getheight(node* p){
if(p){
return p->height;
}
else{
return 0;
}
}
int balancefactor(node* p){
return getheight(p->right)-getheight(p->left);
}
void fixheight(node* p){
int hl=getheight(p->left);
int hr=getheight(p->right);
if (hl>hr){
p->height=hl+1;
}
else{
p->height=hr+1;
}
}node* rotateright(node* p){
node*q=p->left;
p->left=q->right;
q->right=p;
fixheight(p);
fixheight(q);
return q;
}

node* rotateleft(node* q){
node*p=q->left;
q->right=p->left;
p->left=q;
fixheight(q);
fixheight(p);
return p;
}

node* balance(node* p){
fixheight(p);
if(balancefactor(p)==2){
if(balancefactor(p->right) < 0){
p->right=rotateright(p->right);
}
return rotateleft(p);
}
if (balancefactor(p)==-2){
if(balancefactor(p->left)>0){
p->left=rotateleft(p->left);
}
return rotateright(p);
}
return p;
}
node* insert(node* p, int k){
if (!p) return new node(k);
if(k<p->key){
p->left=insert(p->left, k);
}
else{
p->right=insert(p->right, k);
}
return balance(p);
}

node* findmin(node* p){
if (p->left){
return findmin(p->left);
}
else{
return p;
}
}

node* removemin(node* p){
if(p->left==0){
return p->right;
}
p->left=removemin(p->left);
return balance(p);
}node* remove(node* p, int k){
if(!p) return 0;
if(k<p->key){
p->left=remove(p->left, k);
}
else if (k>p->key){
p->right=remove(p->right, k);
}
else{ //k==p->key
node* q=p->left;
node* r=p->right;
delete p;
if(!r) return q;
node* min = findmin(r);
min->right=removemin(r);
min->left=q;
return balance(min);
}
return balance(p);
}

};int main(){
node *root = NULL;
root->insert(root, 10);
root->insert(root, 20);
root->insert(root, 30);
root->insert(root, 40);
root->insert(root, 50);
root->insert(root, 25);
root->remove(root, 25);
int c =root->getheight(root);
cout<<c;

}

Итак, вы можете понять меня, почему мой getheight не работает? Или есть ошибка в вставке (но я полагаю, вставка работает, но может быть, я ошибаюсь). Заранее спасибо.

0

Решение

int main(){
node *root = NULL;
root->insert(root, 10);
root->insert(root, 20);
root->insert(root, 30);
root->insert(root, 40);
root->insert(root, 50);
root->insert(root, 25);
root->remove(root, 25);
int c =root->getheight(root);
cout<<c;

}

Вы используете указатель, инициализированный для NULL как будто это указывает на реальный случай node,

0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector