我现在一直在研究这个项目,我遇到了这个我无法解决的问题。
作为前言,程序根据文件中的数据构建二叉树,然后树可以增长,新的完整信息将写在原始文件上。
要使用单个信息向量执行此操作,我的输入向量按顺序排序,但是(据我所知,如果我错了请纠正我),为了做到这一点,我需要在我的向量中考虑NULL空间,并正确地重写所有内容我需要faux-NULL(填充空间但不包含除指针之外的任何实际信息的节点)我的树上的节点。
当树长大时,我正在尝试完成并使用“NULL”节点来平衡它,并且我会以有序遍历和深度为基础递归地进行。然而,当我运行它时,我遇到了分段错误,当我使用调试器逐步运行它时,我得到
Cannot open file: ../../../../../src/gcc-4.9.2/libgcc/unwind-sjlj.c
特异性。当在递归遍历期间,算法添加一个节点,并且在到达节点的内存分配器的“返回”部分时,会出现错误弹出并且程序中断。
这是我的代码错误还是Code :: Blocks库的错误?
相关代码:
struct Node
{
int idx; //idx is information relevant to the program but not to the structure
std::string phrase;
Node* left, * right;
};
Node* newNode(std::string data, int idx) //memory allocator
{
Node* node = new Node;
node->phrase = data;
node->idx = idx;
node->left = node->right = NULL;
return (node); //right here is where the debugger gives me the error
}
// Function to insert nodes in level order
Node* insertLevelOrder(std::string arr[], int idx[], Node* root,int i, int n)
{
// Base case for recursion
if (i < n)
{
Node* temp = newNode(arr[i],idx[i]);
root = temp;
// insert left child
root->left = insertLevelOrder(arr,idx,root->left, 2 * i + 1, n);
// insert right child
root->right = insertLevelOrder(arr,idx,root->right, 2 * i + 2, n);
}
return root;
}
int calcularProfundidad(Node * root) //Sorry for the spanglish--this is "calculateDepth"
{
if (root == NULL)
{
return 0;
}
int h1 = calcularProfundidad(root->left); //recursively calculate depth of left subtree
int h2 = calcularProfundidad(root->right); //and of right subtree
return 1 + max(h1,h2);
}
void rellenarNulos(Node * root, int prof, int counter) //fills "empty spaces" with "faux-NULL" nodes
{
if(counter == prof) //if reaches depth, stops, if not, adds more nodes
return;
if(root->left == NULL && counter < prof)
{
Node * auxNode = newNode("NULL",0); //error in this call
root->left = auxNode;
}
if(root->right == NULL && counter < prof)
{
Node * auxNode2 = newNode("NULL",0);
root->right = auxNode2;
}
rellenarNulos(root->left,prof,counter++);
rellenarNulos(root->right,prof,counter++);
}
#include <iostream>
#include <fstream>
#include <string>
#include "arbLib.hpp"
using namespace std;
int main()
{
//Builds tree from file
int N;
fstream myfile ("test.txt");
if (!myfile.is_open())
{
cout << "Unable to open file" << endl;
return 0;
}
myfile >> N; //N is the number of nodes
string words[N];
for(int i=0;i<N;i++)
myfile >> words[i];
int nums[N];
for(int j=0;j<N;j++)
myfile >> nums[j];
myfile.close();
//Builds tree from these vectors that are level order
Node *root = insertLevelOrder(words,nums,root,0,N);
int prof = calcularProfundidad(root); //calculates depth
rellenarNulos(root,prof,1); //here is where the program dies
inOrder(root);
destroyTree(root);
cout << endl;
return 0;
}