[英]Binary search tree insertion
需要幫助來弄清楚為什么以下基本二進制搜索樹插入代碼不起作用。 由於我一直在研究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();
}
在我看來
Insert(cRoot->data, cRoot->lChild);
應該是
Insert(newData, cRoot->lChild);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.