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

VS Code运行BST校验代码时出现exited with code=3221225725错误的原因

校验二叉搜索树(BST)的C++代码运行错误分析

运行以下校验二叉搜索树的C++代码时,出现错误:exited with code=3221225725,代码如下:

//holds the previous node value for checking the BST
int previous = INT_MIN;    
//This function simply checks that whether the given binary tree is a BST or not.
bool isBST(Node *root){
    if(root==NULL){
        return true;
    }
    if(isBST(root->left)==false){    //check for roots left subtree
        return false;
    }
    if(root->key <= previous){      //setting the root key value as previous
        return false;
    }
    previous=root->key;             //checking for right subtree
    return (isBST(root->right));
}

int main(){
    Node *root = new Node(4);  
    root->left = new Node(2);  
    root->right = new Node(5);  
    root->left->left = new Node(1);  
    root->left->right = new Node(3);  
      
    if(isBST(root))  
        cout<<"Is BST";  
    else
        cout<<"Not a BST";  
          
    return 0;
}

错误原因解析

错误码3221225725对应Windows系统中的内存访问违规(STATUS_ACCESS_VIOLATION),结合代码来看,主要触发点如下:

  1. 缺少Node结构体定义
    代码直接使用Node类型但未给出定义,编译器无法识别其内存布局,执行new Node(...)时会分配非法内存,最终引发访问违规。

  2. 缺失必要的头文件

    • 使用INT_MIN需要包含<climits>头文件,若未包含,INT_MIN会被视为未定义标识符,触发未定义行为进而导致内存访问错误。
    • 使用cout需要包含<iostream>头文件,缺少该头文件会导致标准输出相关的内存访问异常。
  3. 全局变量previous的边界逻辑问题
    若二叉树中存在值为INT_MIN的节点,第一次校验时root->key <= previous(即INT_MIN <= INT_MIN)会直接返回false,误判合法的BST;若INT_MIN未正确定义,还会间接加剧内存访问违规问题。

修复建议

  • 补充Node结构体定义:
    struct Node {
        int key;
        Node* left;
        Node* right;
        Node(int val) : key(val), left(nullptr), right(nullptr) {}
    };
    
  • 添加上必要的头文件:
    #include <iostream>
    #include <climits>
    using namespace std;
    
  • 替换全局变量previous,改用引用传递避免复用问题,优化后的isBST函数:
    bool isBST(Node* root, int& previous) {
        if (root == nullptr) return true;
        if (!isBST(root->left, previous)) return false;
        if (root->key <= previous) return false;
        previous = root->key;
        return isBST(root->right, previous);
    }
    
    // 调用时初始化previous
    int main() {
        // ... 树的构建代码 ...
        int prev = INT_MIN;
        if (isBST(root, prev))
            cout << "Is BST";
        else
            cout << "Not a BST";
        return 0;
    }
    

内容的提问来源于stack exchange,提问作者Nitish Kumar Mishra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 08:55:22