간단한 BST (Binary Search Tree) 클래스를 작성하려고합니다.손상된 포인터 - BST - 디버그
단일 노드 (eg.value = 10)를 추가하면 루트가 업데이트되고 BST :: insert (...) 끝에 VS C++ 디버거를 사용하여 확인됩니다.
그런 다음 (Case 문 3) 노드 (값 -10)를 표시하려고했지만 아무 것도 인쇄되지 않습니다. 이유는 getRoot()가 호출 될 때 루트가 NULL (?? !!!)입니다.
누군가이 문제를 디버그하도록 도와 줄 수 있습니까?
#include <iostream>
#include <stdio.h>
#include "bst_node.h"
class BST{
private:
bst_node *root;
public:
bst_node* getRoot();
void insert(bst_node *, int val);
void deleteValue(int val);
void display(bst_node *);
void destroy();
BST()
{
root = NULL;
std::cout<<"BST constructor"<<"\n";
}
~BST()
{
std::cout<<"BST destructor"<<"\n";
}
};
int main()
{
int item;
int choice;
BST tree1;
while(1)
{
printf("\n Choices are:\n");
printf("\n 1.Insertbeg\n\n 2.deleteNode\n\n 3.display\n\n 4.exit\n\n");
printf(" Enter U'r choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
printf("Enter element to be inserted: ");
scanf("%d",&item);
tree1.insert(tree1.getRoot(), item);
break;
}
case 2:
{
printf("Enter element to be deleted: ");
scanf("%d",&item);
// tree1.deleteValue(item);
break;
}
case 3:
{
tree1.display(tree1.getRoot());
break;
}
case 4:
exit(1);
break;
default: printf("INVALID CHOICE TRY AGAIN\n");
}
}
}
void BST::insert(bst_node* root, int val)
{
if(root == NULL)
{
// add first element
bst_node *new_node = bst_node::create_empty_node();
new_node->val = val;
root = new_node;
}
else if(val < root->val)
{
insert(root->l_child, val);
}
else if (val >= root->val)
{
insert(root->r_child, val);
}
}
void BST::display(bst_node *root)
{
if(root == NULL)
{
return;
}
else
{
std::cout << root->val <<"\n";
display(root->l_child);
display(root->r_child);
}
}
void BST::deleteValue(int val)
{
std::cout<< " Do nothing";
}
bst_node* BST::getRoot()
{
return root;
}
bst_node.h
class bst_node
{
public:
int val;
bst_node *l_child;
bst_node *r_child;
static bst_node* create_empty_node();
};
bst_node* bst_node::create_empty_node()
{
bst_node *new_node;
new_node = new bst_node;
new_node -> l_child = new_node -> r_child = NULL;
return(new_node);
}
'create_empty_node' 메소드는 어디에 있습니까? –
'root'라는 private 멤버를 'insert()''root'라는 이름으로 숨기고 있습니다. 'root'에 대한 모든 수정은 로컬 변수에 적용됩니다. – amit