思路很简单,做过这个题目一下子就写出来了,关键是小心二维数组中对未知维度的话不能轻易进行比如res[i]操作,必须给他前提分配空间,所以看下:
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector <vector <int>> ret;
if (!root) {
return ret;
}
queue <TreeNode*> q;
q.push(root);
int count=-1;
while (!q.empty()) {
int currentLevelSize = q.size();
count++;
ret.push_back(vector <int> ());//给你一个空间,但是不给元素,可以对这个空间操作了,括号里面是空间数量,我们不知道可以先放着,没事!
for (int i = 1; i <= currentLevelSize; ++i) {
auto node = q.front(); q.pop();
ret[count].push_back(node->val);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
}
return ret;
}
};
我的写法:
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
vector<vector<int> > levelOrder(TreeNode* root) {
vector<vector<int>> res;
if(root==nullptr)
return res;
queue<TreeNode *> q;
q.push(root);
int count=-1;
while(!q.empty()){
vector<int> temp;
int size=q.size();
for(int i=0; i<size;i++){
TreeNode* node=q.front();
q.pop();
temp.push_back(node->val);
if(node->left)
q.push(node->left);
if(node->right)
q.push(node->right);
}
res.push_back(temp);
}
return res;
}
};
下面是N叉树的层序遍历:
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector<vector<int>> levelOrder(Node* root) {
vector<vector<int>>res;
if(root==nullptr)
return res;
queue<Node*> q;
q.push(root);
while(!q.empty()){
vector<int> temp;
int size=q.size();
while(size--){
Node* nroot=q.front(); q.pop();
temp.push_back(nroot->val);
for(auto & i:nroot->children)
q.push(i);
}
res.push_back(temp);
}
return res;
}
};