![](/img/trans.png)
[英]Binary Search Tree with multiple child and two nodes pointing left and right
[英]C Binary search tree not assigning values to left and right nodes?
我似乎遇到一个问题,当我向二进制搜索树中分配值时,根将接受输入的第一个值,但之后再不输入其他任何值。 如果我直接查看root-> left或root-> right,它只会返回null。 我凝视了这么久,以至于不知所措。 我确定递归确实存在一些基本错误,但是我看不到它。 看到我在哪里出错了,我将不胜感激。
#include <stdio.h>
#include <stdlib.h>
#include "Bst.h"
int main(int argc, char** argv) {
int value;
TreeNode* root = NULL;
printf ("Enter an integer\n");
scanf ("%d", &value);
while (value > 0) {
root = insert (value, root);
printf ("Enter an integer\n");
scanf ("%d", &value);
}
printf("The inorder traversal of the tree\n");
inOrder(root);
printf("\n");
printf("The preorder traversal of the tree\n");
preOrder(root);
printf("\n");
return (EXIT_SUCCESS);
}
TreeNode* insert(int newValue, TreeNode* root) {
TreeNode* temp = NULL;
//Sets a value to the root
if (root == NULL) {
temp = (TreeNode*)malloc(sizeof(TreeNode));
temp -> value = newValue;
temp -> left = NULL;
temp -> right = NULL;
return temp;
}
//Will put a larger value to the right within the tree
else if (newValue > (root -> value)) {
temp = insert(newValue, (root -> right));
}
//Will put a smaller value to the left
else {
temp = insert (newValue, (root -> left));
}
return root;
}
void inOrder(TreeNode* root){
if(root == NULL){
return;
}
else {
inOrder(root -> left);
printf("%d", root -> value);
printf(" ");
inOrder(root -> right);
}
return;
}
void preOrder(TreeNode* root){
if(root == NULL) {
return;
} else {
preOrder(root -> right);
printf("%d", root -> value);
printf(" ");
preOrder(root -> left);
}
return;
}
更改:
temp = insert(newValue, (root -> right));
至
root->right = insert(newValue, (root -> right));
同样,以相同方式更改左侧版本。 现在,您正在分配子节点,但从未将它们分配给右或左指针。 他们本质上被扔掉了。
可以肯定的是,错误是您将新插入的左右节点分配给temp
而不是root->right
和root->left
,这会使它们悬在树外。
更改这些行:
//Will put a larger value to the right within the tree
else if (newValue > (root -> value)){
temp = insert(newValue, (root -> right));
}
//Will put a smaller value to the left
else{
temp = insert (newValue, (root -> left));
}
对此:
//Will put a larger value to the right within the tree
else if (newValue > (root -> value)) {
root->right = insert(newValue, (root -> right));
}
//Will put a smaller value to the left
else {
root->left = insert (newValue, (root -> left));
}
此更改使您的代码在我测试时可以按预期工作; inOrder和preOrder都给出了正确的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.