题目没什么说的就是树的层次遍历,但是要考虑树为空的情况。而且对于Vector必须是先申请一个小Vector,对其操作完成后再将其加入大的Vector中。不能V[i].push_back(),因为这时候V[i]还不存在。
/**
* Definition for binary tree
* 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) {
queue<TreeNode* > Q;
vector<vector<int> >V;
Q.push(root);
if (root==NULL) return V;
queue<TreeNode*> tmp ;
while(!Q.empty()) {
vector<int> v1;
while(!Q.empty()) {
TreeNode* pn = Q.front(); Q.pop();
v1.push_back(pn->val);
if (pn->left)
tmp.push(pn->left);
if (pn->right)
tmp.push(pn->right);
}
V.push_back(v1);
while (!tmp.empty()) {
Q.push(tmp.front());
tmp.pop();
}
}
return V;
}
};
测试代码
#include <queue>
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
vector<vector<int> > levelOrder(TreeNode *root) {
queue<TreeNode* > Q;
vector<vector<int> >V;
Q.push(root);
if (root==NULL) return V;
queue<TreeNode*> tmp ;
while(!Q.empty()) {
vector<int> v1;
while(!Q.empty()) {
TreeNode* pn = Q.front(); Q.pop();
v1.push_back(pn->val);
if (pn->left)
tmp.push(pn->left);
if (pn->right)
tmp.push(pn->right);
}
V.push_back(v1);
while (!tmp.empty()) {
Q.push(tmp.front());
tmp.pop();
}
}
return V;
}
int main() {
TreeNode* h = new TreeNode (1);
h->right = new TreeNode(2);
h->left = new TreeNode(3);
h->right->left = new TreeNode(4);
h->right->left->left = new TreeNode(5);
vector<vector<int>> V = levelOrder(h);
for (int i=0;i<V.size();i++) {
for (int j=0;j<V[i].size();j++) {
cout<<V[i][j] <<" ";
}
cout<<endl;
}
}