首页 > 解决方案 > 错误:使用递归时来自 abort(3) (SIGABRT) 的中止信号

问题描述

问题陈述:从给定的中序序列表 构造二叉树。

我能够编写逻辑,但我得到了错误 Abort signal from abort(3) (SIGABRT),我无法找到导致此错误的原因。

代码:

#include <iostream>
#include <vector>
#include<algorithm>
#include <map>
#include <cmath>

using namespace std;

struct Node{
    int key;
    Node *left, *right;
    Node(int key){
    {
        this->key=key;
        this->left=this->right=nullptr;
    }
    }
};


class Solution {
public:

Node *construct_bin(int pidx, int s, int e, map<int, int>  m, vector<int> pre){

    if (s>e){
        return nullptr;
    }
    Node * root = new Node(pre[pidx++]);

    int i = m[root->key];
    root->left = construct_bin(pidx, s, i-1, m, pre);
    root->right = construct_bin(pidx, i+1, e, m, pre);

    return root;

}
};



int main()
{
    Solution sol;
    /* Construct the following tree
               1
             /   \
            /     \
           2       3
          /       / \
         /       /   \
        4       5     6
               / \
              /   \
             7     8
    */

    vector<int> inorder = { 4, 2, 1, 7, 5, 8, 3, 6 };
    vector<int> preorder = { 1, 2, 4, 3, 5, 7, 8, 6 };
    map<int, int> m;
    int co=0;
    for (auto it: inorder){
        m[it] = co++;
    }
    int n = preorder.size();
    Node* x = sol.construct_bin(0,0,n-1,m, preorder);
}

逻辑:

逻辑:

标签: c++recursion

解决方案


您增加pidxin construct_bin,但您不使用该增加的值做任何事情。结果,您调用construct_bin了无数次,您的代码最终会耗尽内存或溢出堆栈。


推荐阅读