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

C++创建两个不同二叉树时触发Segmentation Fault问题排查

问题根源分析与修复方案

首先,触发Segmentation Fault的最直接原因是你在main函数里声明的head和second这两个二叉树根指针没有初始化!在C++中,局部指针变量如果不手动赋值,会变成野指针(指向内存中随机的地址),而不是你默认以为的NULL。

当你第一次调用AddNode(head, i)时,head是野指针,head == NULL的判断不成立,代码会直接尝试访问head->leftchild——这相当于访问一块不属于你的内存,直接触发段错误。单个树的时候可能是运气好(比如野指针刚好指向了一块暂时没被使用的内存),但这是未定义行为,绝对不能依赖。

除此之外,你的代码还有两个关键问题:

1. AddNode函数的逻辑完全错误,根本不是二叉树的插入逻辑

当前的AddNode只能给根节点添加左、右两个孩子,之后所有调用都会覆盖根节点的右孩子,完全没有实现二叉树的递归插入或者层级插入逻辑。比如循环11次的话,最后根节点的右孩子会被赋值11次,之前的节点全部丢失,而且根本没有构建出多节点的二叉树。

2. PrintTree函数里的exit使用错误

exit是一个需要传入退出码的函数(比如exit(0)),而且你在这里的逻辑是遇到空节点就返回,不是退出整个程序,应该用return;替代。另外,打印指针地址的方式也没有意义,应该打印节点的data值。


修正后的代码示例

下面是修复了所有问题的代码,实现了二叉树的层级插入(按顺序构建完全二叉树),同时修复了指针初始化、打印逻辑等问题:

#include<iostream>
#include<queue> // 用于层级插入
using namespace std;

struct tree {
    int data;
    struct tree *leftchild;
    struct tree *rightchild;
};
typedef struct tree* Binary_tree;

// 创建新节点
Binary_tree CreateNode(int value) {
    Binary_tree temp = new struct tree;
    temp->data = value;
    temp->leftchild = NULL;
    temp->rightchild = NULL;
    return temp;
}

// 层级插入节点(构建完全二叉树)
Binary_tree AddNode(Binary_tree head, int value) {
    Binary_tree newNode = CreateNode(value);
    if (head == NULL) {
        return newNode;
    }
    // 使用队列实现层级遍历,找到第一个有空孩子的节点
    queue<Binary_tree> q;
    q.push(head);
    while (!q.empty()) {
        Binary_tree current = q.front();
        q.pop();
        if (current->leftchild == NULL) {
            current->leftchild = newNode;
            break;
        } else {
            q.push(current->leftchild);
        }
        if (current->rightchild == NULL) {
            current->rightchild = newNode;
            break;
        } else {
            q.push(current->rightchild);
        }
    }
    return head;
}

// 前序遍历打印二叉树
void PrintTree(Binary_tree head) {
    if (head == NULL) {
        return;
    }
    // 前序:根 -> 左 -> 右
    cout << head->data << " ";
    PrintTree(head->leftchild);
    PrintTree(head->rightchild);
}

int main() {
    // 初始化根指针为NULL!
    Binary_tree head = NULL;
    Binary_tree second = NULL;
    
    for(int i=1;i<12;i++) {
        head = AddNode(head,i);
        second = AddNode(second,i+2);
    }
    
    cout << "Tree head (前序遍历): ";
    PrintTree(head);
    cout << endl;
    
    cout << "Tree second (前序遍历): ";
    PrintTree(second);
    cout << endl;
    
    return 0;
}

关键修复点总结

  • 局部指针变量必须显式初始化为NULL,避免野指针问题;
  • 重写AddNode函数,使用队列实现层级插入,正确构建多节点二叉树;
  • 修复PrintTree的退出逻辑,改为return,并实现有意义的前序遍历打印;
  • 移除了无意义的指针地址打印,改为打印节点的实际数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:49:39