学习资料:
①二维数组的赋值:
vector型二维数组赋值问题_二维vector赋值-CSDN博客
没查到二维数组没有确定大小的赋值方法。要么push_back(一维数组);要么先定义行,再遍历行并resize(列)。
②队列queue的函数:
队列queue常用的函数:
- push() 在队尾插入一个元素
- pop() 删除队列第一个元素(不返回值)
- size() 返回队列中元素个数
- empty() 如果队列空则返回true
- front() 返回队列中的第一个元素
- back() 返回队列中最后一个元素
数组vector用到的函数:
push_back()
自己写的:
和之前刷前序遍历、中序遍历、后序遍历一样,想用递归,但是二维数组不好赋值。报错的代码如下:
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型vector<vector<>>
*/
void fun(int dex, vector<vector<int>>& l, TreeNode* root){
if(root == NULL)
return;
l[dex].push_back(root->val); //报错
fun(dex + 1, l, root->left);
fun(dex + 1, l, root->right);
}
vector<vector<int> > levelOrder(TreeNode* root) {
// write code here
vector<vector<int>> l;
fun(0, l, root);
return l;
}
};
刷题模板的:
注意,有两个循环!
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型vector<vector<>>
*/
vector<vector<int> > levelOrder(TreeNode* root) {
// write code here
vector<vector<int>> res;
if(root == NULL)
return res;
queue<TreeNode*> q; // queue,队列,先入先出。注意定义是“queue<> q”.
q.push(root);
while (!q.empty()) { // 不是 q != NULL
int n = q.size();
vector<int> row;
for (int i = 0; i < n; i++) {
row.push_back(q.front()->val);
if (q.front()->left)
q.push(q.front()->left);
if (q.front()->right)
q.push(q.front()->right);
q.pop(); // python的pop是删除最后一个元素,queue的pop是删除第一个元素。
}
res.push_back(row);
}
return res;
}
};