0
저는 oop 프로그래밍의 새로운 기능이므로이 질문은 nooby로 보입니다. 미안해. 그래서, 여기 내 AVL 트리 구현, 여기에 함수 삽입 및 삭제 잘 작동하고 있다고 가정하지만, getheight 나에게 어떤 경우에 0을 제공합니다.AVL 트리는 트리의 높이를 계산할 수 없습니다
#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가 작동하지 않는 이유는 무엇입니까? 또는 삽입에 오류가 있습니다 (하지만 삽입 작업이 있다고 가정합니다. 그러나 잘못되었을 수 있습니다). 미리 감사드립니다.
디버거를 사용할 때 어떤 질문에 답해 줄 수 있습니까? –