0
需要帮助了解为什么下面的基本二叉搜索树插入代码不起作用。由于我一直在使用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();
}
啊!谢谢,现在它工作。 – Nemo