【发布时间】:2019-04-17 06:21:17
【问题描述】:
我已经编写了用于插入二叉搜索树及其遍历的代码。
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。
我无法找出代码中的问题。我的插入逻辑有什么问题?
【问题讨论】:
-
你 while 条件不正确.. 调试它并查看你当前的树结构以及为什么 while 正文会被跳过它不应该的地方
标签: c++ binary-tree binary-search-tree dynamic-programming