我試圖解決這個問題
https://practice.geeksforgeeks.org/problems/construct-an-expression-tree/1?utm_source=gfgpractice#
問題:為給定的后綴運算式創建運算式樹
我的方法:我嘗試維護一堆節點并使用通用后綴評估方法生成一棵樹,其中給定運算子的結果將是節點本身,但具有修改的左右指標。
但我遇到了錯誤。
Segmentation Fault (SIGSEGV)
Learn More about
Seg Fault
// { Driver Code Starts
#include<bits/stdc .h>
using namespace std;
struct et
{
char value;
et* left, *right;
et(char x){
value = x;
left = right = NULL;
}
};
bool isOperator(char c)
{
if (c == ' ' || c == '-' ||
c == '*' || c == '/' ||
c == '^')
return true;
return false;
}
void inorder(et *t)
{
if(t)
{
inorder(t->left);
printf("%c ", t->value);
inorder(t->right);
}
}
et* constructTree(char []);
int main()
{
int t;
cin>>t;
while(t--){
char postfix[25];
cin>>postfix;
et* r = constructTree(postfix);
inorder(r);
cout<<endl;
}
return 0;
}// } Driver Code Ends
/*struct et
{
char value;
et* left, *right;
};*/
//function to construct expression tree
et* constructTree(char postfix[])
{
//code here
stack<et> operand;
et *root=NULL;
for(int i=0;postfix[i] != '\0'; i){
if(postfix[i]>='a' && postfix[i]<='z'){
et node = et(postfix[i]);
//cout<<node.value<<" "<<node.left<<" "<<node.right<<"\n";
operand.push(node);
/*et nod = operand.top();
cout<<nod.value<<" "<<nod.left<<" "<<nod.right<<"\n";
operand.pop();
operand.push(nod);
et *no = &(operand.top());
cout<<no->value<<" "<<no->left<<" "<<no->right<<'\n';*/
}
else{
et right1=operand.top();
operand.pop();
et left1=operand.top();
operand.pop();
et node = (et(postfix[i]));
node.left = &left1;
node.right= &right1;
operand.push(node);
root=&(operand.top());
//cout<<node.value<<" "<<node.left<<" "<<node.right<<"\n";
//inorder(root);
}
}
//root=NULL;
return root;
}
誰能告訴我該怎么做才不會出錯?
uj5u.com熱心網友回復:
問題就在這里
node.left = &left1;
left1是一個區域變數,將被銷毀。所以在那之后你訪問了一個無效的地址。
你可以使用這樣的東西
node.left = new er(left1);
但是您應該首先將指標存盤在堆疊中。
uj5u.com熱心網友回復:
在 function 中constructTree,您不執行任何動態記憶體分配。因此,無論您從該函式回傳什么記憶體指標,當您在該函式之外時,它都指向無效記憶體。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/406183.html
標籤:
