You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言二叉搜索树节点搜索程序输出异常问题求助

二叉搜索树搜索程序固定输出问题排查

问题现象

编写基于二叉搜索树的节点搜索C语言程序,运行时始终输出相同结果,无法定位错误位置。已尝试修改变量排查、多种调试手段均未修复,原始代码(已修正注释排版错误)如下:

#include <stdio.h>
#include <stdlib.h>

// Basic struct of Tree
struct node
{
    int data;
    struct node *left;
    struct node *right;
};

// Function to create a new Node
struct node *createNode(int item)
{
    struct node *newNode = malloc(sizeof(struct node));
    newNode->left = NULL;
    newNode->right = NULL;
    newNode->data = item;
    return newNode;
}

int search(struct node *root, int value)
{
    if (root == NULL)
        return 0;
    if (root->data == value)
        return 1;
    if (root->data < value)
        return search(root->right, value);
    else
        return search(root->left, value);
}

int main()
{
    // struct node *root = NULL;
    struct node *root = createNode(1);
    root->left = createNode(2);
    root->right = createNode(3);
    root->left->left = createNode(4);
    root->left->right = createNode(5);
    root->right->right = createNode(6);
    root->left->right->left = createNode(7);
    root->left->right->right = createNode(8);
    root->right->right->left = createNode(9);

    int item = 34;

    // Function to find item in the tree
    int found = search(root, item);

    if (found)
        printf("%d value is found in the tree", item);
    else
        printf("%d value not found", item);

    return 0;
}

根本原因

你的search函数是严格按照二叉搜索树(BST)规则编写的二分查找逻辑:默认任意节点的左子树所有节点值小于当前节点,右子树所有节点值大于当前节点,每次比较后只需要走其中一个分支即可。
但你手动构建的树完全不符合BST的核心规则:

  • 根节点值为1,左子节点赋值为2(2>1,违反左子节点小于父节点的要求)
  • 值为2的节点左子节点赋值为4(4>2,违反规则)
  • 值为6的节点左子节点赋值为9(9>6,违反规则)

错误的树结构导致搜索路径完全偏离实际节点存储位置:比如搜索实际存在的节点2时,逻辑判断1<2会直接走到右子节点3,后续永远遍历不到存储2的左子树分支,最终除了1、3、6三个在搜索路径上的节点,搜索其他任何值(包括树中真实存在的2、4、5、7、8、9)都会返回未找到,表现为输出结果始终不变。

修复方法

根据实际需求二选一即可:

  • 如果要实现BST搜索:手动构建树时严格遵守左小右大的规则,或实现标准的BST插入函数来构建树,不要手动随意挂载左右节点。
  • 如果操作的是普通二叉树而非BST:替换现有二分搜索逻辑,改为前/中/后序全遍历所有节点查找目标值。

补充:代码注释周围多余的*属于排版错误,不会影响程序运行,删除即可。

内容的提问来源于stack exchange,提问作者ravi prakash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 03:57:20