c++ - 错误:使用递归时来自 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);
}
逻辑:
解决方案
您增加pidx
in construct_bin
,但您不使用该增加的值做任何事情。结果,您调用construct_bin
了无数次,您的代码最终会耗尽内存或溢出堆栈。
推荐阅读
- javascript - 未定义的'appendChild'
- mysql - 静默变量赋值
- swift - 如何通过使用日期选择器单击左右箭头来显示前一天/下一天
- java - 按边标签对顶点组的传入顶点进行分组
- powershell - 用于从网络计算机获取特定系统信息的 PowerShell 脚本
- spring-boot - @Value 注释字段返回 @Service 注释类的 null 方法
- ibm-watson - 是否可以让 Watson Assistant 在 IBM Cloudant 上搜索数据?
- perl - 模板失败后如何调用 Mojolicious 控制器方法
- c++ - 使用星期几的类
- spring-boot - Spring 具有两种安全配置 - 失败的 API 登录重定向到表单登录页面。如何改变?