Исходный код Leetcode: https://leetcode.com/explore/interview/card/top-interview-questions-easy/94/trees/628/
Когда я изменяю строку 23 на while (result.size() < t.second+1)
, она работает нормально, но не работает, когда у меня while (result.size()-1 < t.second)
. Разве это не эквивалентные выражения? Почему я получаю эту ошибку?
Line 922: Char 34: runtime error: reference binding to null pointer of type 'struct value_type' (stl_vector.h)
Мой код:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> result;
if (root == NULL)
return result;
queue<pair<TreeNode*, int>> q;
q.push(make_pair(root, 0));
while (!q.empty())
{
pair<TreeNode*,int> t = q.front();
q.pop();
while (result.size()-1 < t.second)
result.push_back({});
result[t.second].push_back(t.first->val);
if (t.first->left != NULL)
q.push(make_pair(t.first->left, t.second+1));
if (t.first->right != NULL)
q.push(make_pair(t.first->right, t.second+1));
}
return result;
}
};