二进制搜索树无法正确识别值

Sac*_*ith 0 c binary-search-tree data-structures

我正在尝试使用C实现二进制Serach树.在此代码中,我向树中添加了几个值,然后尝试检查这些值是否在树中.但我尝试的代码总是返回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;
}
Run Code Online (Sandbox Code Playgroud)

我在这里错过了什么?

提前致谢.

Jen*_*ens 5

你错过了

num =scanf("%d");
Run Code Online (Sandbox Code Playgroud)

没有做你认为它做的事(scanf返回成功转换的项数或-1 EOF).您没有将编译器的警告级别设置得足够高,以告诉您需要

if (scanf ("%d", &num) != 1) {
    /* complain */
}
Run Code Online (Sandbox Code Playgroud)

在你破碎的程序中,scanf()恰好返回1(因为它转换了1个项目并将其写入随机内存)并且因为树中有1,所以你总是得到真实.