[英]Problem with insertion in Binary Search Tree
我已經編寫了一個用於在二叉搜索樹中插入及其遍歷的代碼。
class node
{
public:
int data;
node *left;
node *right;
};
node* createNode(int value)
{
node *temp = new node;
temp->data = value;
temp->left = NULL;
temp->right = NULL;
return temp;
}
node *start = NULL;
void insertNode(int val)
{
if (start == NULL)
{
start = createNode(val);
return;
}
node *temp = start;
while ((temp->left != NULL) && (temp->right != NULL))
{
if (val < temp->data)
{
temp = temp->left;
}
else if (val > temp->data)
{
temp = temp->right;
}
else
{
cout << "Already exists in tree\n";
return;
}
}
if (val < temp->data)
{
temp->left = createNode(val);
return;
}
else
{
temp->right = createNode(val);
return;
}
}
void inorder(node *root)
{
if (root != NULL)
{
inorder(root->left);
printf("%d \n", root->data);
inorder(root->right);
}
}
在某些測試用例上它不能正常工作。
例如,如果插入 15、25 和 35,然后遍歷樹,它只會打印 15 和 25。
我無法找出代碼中的問題。 我的插入邏輯有什么問題?
讓我們來看看行為 -
if (start == NULL)
NULL
的起始節點。(temp->left != NULL) && (temp->right != NULL)
(val < temp->data)
這個檢查創建一個正確的節點。(temp->left != NULL) && (temp->right != NULL)
(val < temp->data)
這個檢查創建一個右節點(替換當前的右節點)。 這是不對的。您需要更正此處的 while 循環條件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.