【问题标题】:Can someone please find the error in code. Gives runtime error "Segmentation Fault" .Expression Tree有人可以在代码中找到错误。给出运行时错误“分段错误”。表达式树
【发布时间】:2021-11-05 11:20:58
【问题描述】:

谁能找到代码中的错误。给出运行时错误“分段错误”。表达式树。我正在使用一个变量来保持表达式的值。它是递归程序。请提供它如何陷入分段错误。

这是树数据结构的常见问题。给定一个由基本二元运算符(+、-、*、/)和一些整数组成的完整二元表达式树,您的任务是计算表达式树。

class Solution
{
public:
    /*You are required to complete below method */

    void cal(node* root, stack<string>& sign, stack<int>& num, int& sum)
    {
        if (root == NULL)
        {
            return;
        }

        if (root->data == "+" || root->data == "-" || root->data == "/" || root->data == "*")
        {
            sign.push(root->data);
        }

        else
        {
            num.push(stoi(root->data));
        }

        cal(root->left, sign, num, sum);
        cal(root->right, sign, num, sum);

        int a = num.top();
        num.pop();
        int b = num.top();
        num.pop();
        string sign1 = sign.top();
        sign.pop();

        if (sign1 == "+")
        {
            sum = a + b;
        }

        if (sign1 == "*")
        {
            sum = a * b;
        }

        if (sign1 == "-")
        {
            sum = a - b;
        }

        if (sign1 == "/")
        {
            sum = a / b;
        }

        num.push(sum);
        return;
    }

    int evalTree(node* root)
    {
        // Your code here
        cout << "jh" << endl;
        stack<string> sign;
        stack<int> num;
        int res = 0;
        cal(root, sign, num, res);
        return res;
    }
};

【问题讨论】:

  • 在不知道node 是什么类型、该结构是如何初始化的以及需要什么结果的情况下是不可能的。很可能但很明显,代码固有地存在未定义行为的风险,using namespace std 以及 namespace std 中的用户标识符 defined
  • 1.这不是minimal reproducible example。即使我愿意为您调试它,我也做不到。 2. 这是一个学习调试代码的好机会。调试是软件开发的必备技能,值得学习。仅供参考:What is a debugger and how can it help me diagnose problems?
  • @Scheff'sCat 我很确定这是来自在线法官的代码,或者是设计不佳的计算机辅助教育课程。他们不提供整个程序,只有您必须根据作业中的描述修改的部分。这是基于 40 年软件开发过程的想法。调试的唯一方法是针对测试运行或从程序中打印一些东西。解决这个问题的唯一方法是通过偏执的健全性检查和检查输出来增量构建代码
  • @Swift-FridayPie ...或类似于本地调试的缺失部分。关于在线评委...我相信已经多次提到竞赛网站对学习S/W开发的价值有限... ;-)
  • @Scheff'sCat 我知道。这应该告诉罗马尼亚人、白俄罗斯人或过去几年俄罗斯教育标准设计者,他们实施在线评判方法作为对学生进行测试的唯一方法,这个想法本身就是学校多年来所做的复制副本许多国家,包括法国或德国,但正如我所说,已经过时了几十年。 :P

标签: c++ tree segmentation-fault


【解决方案1】:

节点可以是以下两种形式之一:

  1. data 是一个数字,没有孩子;
  2. data 是运算符,子节点也是节点。

您的代码尝试在这两种情况下都应用运算符。

函数改写如下:

    void cal(node* root, stack<string>& sign, stack<int>& num, int& sum) {
        if (root == NULL) {
            return;
        }

        if (root->data == "+" || root->data == "-" || root->data == "/" || root->data == "*") {
            sign.push(root->data);
        } else {
            num.push(stoi(root->data));
            return; // Stop processing here 
        }

        // rest as before
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-12
    • 1970-01-01
    • 2015-06-22
    • 1970-01-01
    • 2017-05-16
    • 2015-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多