【发布时间】:2015-02-24 08:24:56
【问题描述】:
我似乎有一个问题,当我将值分配到我的二叉搜索树中时,根将接受输入的第一个值,但之后没有输入任何其他值。如果我直接查看 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时数据的去向。 -
查看您的 TreeNode 定义也可能会有所帮助。这是在您的
Bst.h中吗?
标签: c binary-search-tree