我需要帮助找出为什么下面的基本二进制搜索树插入代码不起作用。因为我已经在C#上工作了一段时间了,我恐怕我忘了我的一些C++。此外,任何改进编码风格的建议都会非常有帮助。(我知道我现在还没有释放内存)
struct Node
{
int data;
Node* lChild;
Node* rChild;
Node(int dataNew)
{
data = dataNew;
lChild = NULL;
rChild = NULL;
}
};
class BST
{
private:
Node* root;
void Insert(int newData, Node* &cRoot) //is this correct?
{
if(cRoot == NULL)
{
cRoot = new Node(newData);
return;
}
if(newData < cRoot->data)
Insert(cRoot->data, cRoot->lChild);
else
Insert(cRoot->data, cRoot->rChild);
}
void PrintInorder(Node* cRoot)
{
if(cRoot != NULL)
{
PrintInorder(cRoot->lChild);
cout<< cRoot->data <<" ";;
PrintInorder(cRoot->rChild);
}
}
public:
BST()
{
root = NULL;
}
void AddItem(int newData)
{
Insert(newData, root);
}
void PrintTree()
{
PrintInorder(root);
}
};
int main()
{
BST *myBST = new BST();
myBST->AddItem(5);
myBST->AddItem(7);
myBST->AddItem(1);
myBST->AddItem(10);
myBST->PrintTree();
}发布于 2011-09-24 13:45:24
在我看来
Insert(cRoot->data, cRoot->lChild);应该改为
Insert(newData, cRoot->lChild);https://stackoverflow.com/questions/7537262
复制相似问题