函数返回负值 1。可能是段错误

Function returned negative 1. Might be segfault

所以,我在 lintcode(编号 69)上编写了一个问题。我决定使用使用传统数组作为队列的 dfs。但是,它在注释行返回 -1,lintcode 表示这是给定输入的分段错误。这是我的代码。

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: A Tree
     * @return: Level order a list of lists of integer
     */
    vector<vector<int>> levelOrder(TreeNode * root) {
        vector<vector<int>> result;
        if(root){
            TreeNode* Q[21];
            int f(0),b(0);
            Q[++b]=root;
            while(f<b){
                result.push_back(vector<int>());
                for(int i=b-f;i>0;i--){
                    auto n=Q[f++];
                    result.back().push_back(n->val);//Error occured the third time running this line
                    if(n->left)Q[++b]=n->left;
                    if(n->right)Q[++b]=n->right;
                }
            }
        }
        return result; 
    }
};

输入是 {1,2,3} 作为 TreeNode 的序列。

这两行可能是罪魁祸首:

Q[++b]=root;
...
auto n=Q[f++];

首先,你增加b before使用值作为索引,所以它等同于

Q[1] = root;

在第二行,当你第一次执行它时 f 的值是零,你在 之后增加值 你将它用作索引,所以它相当于

auto n = Q[0];

现在,你还没有初始化Q[0],所以你会得到一个不确定的值,并且有undefined behavior

您需要对两次增加使用相同的顺序,无论是预先还是 post-increase。我建议 post-increase 充分利用数组(记住数组索引是 zero-based)。