我正在尝试编写简单的二叉搜索树类(BST)。
当我添加单个节点(例如,value = 10)时,根会更新,并且我在 BST::insert(...) 末尾使用 VS C++ 调试器进行了验证。
然后我尝试显示(案例陈述 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);
}