我想用C实现一个Binary Serach Tree。在这段代码中,我向树中添加了一些值,然后试图检查这些值是否在树中。但是我的尝试代码总是返回true。二叉搜索树无法正确识别值
我已经检查了很多次。我仍然在学习C编程。
这是我的代码。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct BSTnode {
int data;
struct BSTnode *left;
struct BSTnode *right;
} BSTnode;
BSTnode *getNewNode(int data){
BSTnode *newNode = (BSTnode*)malloc(sizeof(BSTnode));
newNode->data=data;
newNode->left=newNode->right=NULL;
}
BSTnode* InsertNew(BSTnode *root,int data){
if(root == NULL){
root = getNewNode(data);
}
else if(data <= root->data){
root->left = InsertNew(root->left,data);
} else{
root->right = InsertNew(root->right,data);
}
return root;
}
bool search(BSTnode *root, int data){
if(root== NULL) return false;
else if(root->data == data) return true;
else if (data <= root->data) return search(root->left,data);
else return search(root->right,data);
}
int main()
{
//node to store root
BSTnode *root = NULL;
root = InsertNew(root,34);
root = InsertNew(root,4);
root = InsertNew(root,3);
root = InsertNew(root,1);
int num;
printf("enter a number : \n");
num =scanf("%d");
if(search(root,num)==true){
printf("found");
}else{
printf("not found");
}
return 0;
}
我在这里错过了什么?
在此先感谢。
如果你还没有,那么这是学习如何使用调试器* *,以及如何使用它(和其他技术)为*调试*您程序的最佳时机。我建议你花一些时间埃里克利珀阅读[如何调试小程序(https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。 –
并且还在编译时发出警告。例如,当你应该返回新节点时,你不会从'getNewNode'返回任何东西。 –
尝试修复代码的缩进 - 这将有助于您和未来的代码读者。 –