将重复数字添加到二进制搜索树
因此,我正在尝试为二进制搜索树创建一个函数,如果您输入一个已经存在的数字,则该数字将添加到左子树中,而左子树被推下一个步骤。
则可以看到这
如果我们有一棵看起来像
5
/ \
3 6
/ \ \
2 4 9
/
1
并将3插入到这里的树,
5
/ \
3 6
/ \
3 9
/ \
2 4
/
1
但我的代码中发生的每一个数字是插入两次后的每个数字
5
/ \
3 6
/ \ \
3 4 9
/
2
/
2
/
1
/
1
棵树, 。
tree *insert(tree *tree, int data){
if(tree == NULL){
return new(data);
}
if(data > tree->data){
tree->right = insert(tree->right, data);
}
else if(data < tree->data){
tree->left = insert(tree->left, data);
}
else if(data == tree->data){
if(tree->left == NULL){
tree->left = insert(tree->left, data);
}
else if(tree->left != NULL){
struct tree *temp = copy(tree->left);
tree->left->data = data;
tree->left->left = insert(temp, temp->data);
}
}
return tree;
}
谢谢您的帮助!
So I am trying to make a function for a binary search tree where if you input a number that already exists, the number gets added to the left child and the left subtree gets pushed down one step.
To visualize this
if we have a tree that looks like
5
/ \
3 6
/ \ \
2 4 9
/
1
And insert a 3 into here, the tree becomes
5
/ \
3 6
/ \
3 9
/ \
2 4
/
1
But what happens in my code is that every number after the duplicate gets inserted twice so that the result becomes
5
/ \
3 6
/ \ \
3 4 9
/
2
/
2
/
1
/
1
Below is the code I have so far.
tree *insert(tree *tree, int data){
if(tree == NULL){
return new(data);
}
if(data > tree->data){
tree->right = insert(tree->right, data);
}
else if(data < tree->data){
tree->left = insert(tree->left, data);
}
else if(data == tree->data){
if(tree->left == NULL){
tree->left = insert(tree->left, data);
}
else if(tree->left != NULL){
struct tree *temp = copy(tree->left);
tree->left->data = data;
tree->left->left = insert(temp, temp->data);
}
}
return tree;
}
Thank you for helping out!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试以下版本的插入功能。为了您的方便,我添加了评论。希望您会明白的。
让我知道它是否有效。愉快的编码:)
Try the following version of the insert function. I have added comments for your convenience. Hopefully, you will understand.
Let me know if it works. Happy coding :)