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

C++不使用struct纯类实现二叉树插入功能异常求助

错误排查与修复

核心问题点

  • 指针值传递导致插入无效:mainInsert函数的newroot参数是按值传递的指针,函数内给newroot赋值仅修改局部变量,无法同步修改原树的root、子节点left/right指针,所有插入的节点都没有挂载到树上,最终根节点仍为NULL,打印无输出。
  • string::compare返回值判断不规范:compare返回任意负数即代表当前字符串小于对比字符串,不一定固定返回-1,判断==-1可能触发排序逻辑异常。
  • 头文件缺失:使用了string类型但未引入对应头文件,部分编译器会编译失败。
  • 命名不规范:二叉树管理类命名为LinkedList(链表)不符合功能语义。

修正后完整代码

#include<iostream>
#include<string>
using namespace std;

class Tree
{
public:
    Tree* left;
    Tree* right;
    string info;

    Tree()
    {
        this->left = nullptr;
        this->right = nullptr;
        this->info = "";
    }
    Tree(string info)
    {
        this->left = nullptr;
        this->right = nullptr;
        this->info = info;
    }    
    Tree(string info,Tree* left,Tree* right)
    {
        this->left = left;
        this->right = right;
        this->info = info;
    }
};

class BinaryTree
{
public:
    Tree* root;

    BinaryTree()
    {
        root = nullptr;
    }

    // 参数改为指针的引用,修改会同步到实参
    void mainInsert(Tree* &newroot , string info)
    {
        if(newroot == nullptr)
        {
            Tree* newNode = new Tree(info);
            newroot = newNode;
            return;
        }
        // 修改compare判断逻辑
        if(info.compare(newroot->info) < 0)
        {
            mainInsert(newroot->left, info);
        }
        else
        {
            mainInsert(newroot->right, info);
        }
    }

    void mainPrintTree(Tree* newroot)
    {
        if(newroot == nullptr)
        {
            return;
        }
        cout<<newroot->info<<endl;
        mainPrintTree(newroot->left);
        mainPrintTree(newroot->right);
    }

    void insert(string info)
    {
        mainInsert(this->root , info);
    }

    void printTree()
    {
        mainPrintTree(this->root);
    }
};

int main()
{
    BinaryTree myTree;
    myTree.insert("2");
    myTree.insert("1");
    myTree.insert("3");
    myTree.insert("7");
    myTree.insert("0");
    myTree.printTree();
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 22:06:04