我一直在试验二叉树。我正在尝试使用下面的c ++代码构建一个表达式树。但是,我在运行时不断得到segmentation fault(core dumped)
#include<iostream>
#include<ctype.h>
#include<vector>
using namespace std;
struct tree{
char data;
tree *left=NULL;
tree *right=NULL;
tree *parent=NULL;
};
tree* newNode(char d)
{
struct tree* node = new tree;
//struct tree* nodep = &node;
node->data = d;
return node;
}
tree* parseTree(string expression)
{
vector<char> tokens;
for(int i = 0; i<expression.size(); i++)
tokens.push_back(expression[i]);
struct tree* currentNode = newNode(' ');
struct tree* prevNode = new tree;
for(int i = 0; i<tokens.size(); i++)
{
if(tokens[i]=='(')
{
currentNode->left = newNode(' ');
prevNode = currentNode;
currentNode = currentNode->left;
currentNode->parent = prevNode;
}
else if(tokens[i]=='+'||tokens[i]=='-'||tokens[i]=='*'||tokens[i]=='/')
{
currentNode->data = tokens[i];
prevNode = currentNode;
currentNode = currentNode->right;
currentNode->parent = prevNode;
}
else if(isdigit(tokens[i]))
{
currentNode->data = tokens[i];
prevNode = currentNode;
currentNode = currentNode->parent;
}
else if(tokens[i]==')')
{
prevNode = currentNode;
currentNode = currentNode->parent;
}
}
return currentNode;
}
int main()
{
string expression = "(3+(4*5))";
struct tree* root = parseTree(expression);
return 0;
}
我尝试了不同的方法,但是我无法摆脱这个错误
我想念什么? 为什么会出现此错误? 该如何纠正?
答案 0 :(得分:1)
else if(tokens[i]=='+'||tokens[i]=='-'||tokens[i]=='*'||tokens[i]=='/')
{
currentNode->data = tokens[i];
prevNode = currentNode;
currentNode = currentNode->right;
currentNode->parent = prevNode;
}
没有任何代码将right
设置为NULL
以外的任何值。因此,在最后一行中,currentNode
是NULL
,并且您正在取消引用NULL
指针。
另外,在这里看看:
struct tree* prevNode = new tree;
此值从不使用,更改该值后,您在此处分配的tree
就会泄漏。
答案 1 :(得分:1)
这部分使用->right
,从未设置过:
else if(tokens[i]=='+'||tokens[i]=='-'||tokens[i]=='*'||tokens[i]=='/')
{
currentNode->data = tokens[i];
prevNode = currentNode;
currentNode = currentNode->right;
currentNode->parent = prevNode; // SEGFAULT
}
因此,您试图写入地址0 + some offset
,但您不允许这样做。