BFS直接就可以过
#include<iostream>
#include<algorithm>
#include<fstream>
#include<vector>
#include<unordered_map>
#include<stack>
#include<string>
#include<queue>
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)
{
vector<vector<int>> r;
if (root == NULL)
return r;
queue<TreeNode> q;
q.push(*root);
int length;
while (!q.empty())
{
length = q.size();
vector<int> tmp;
for (int i = 0; i < length; i++)
{
TreeNode *temp = new TreeNode(0);
*temp = q.front();
if (temp->left != NULL)
q.push(*temp->left);
if (temp->right != NULL)
q.push(*temp->right);
tmp.push_back(temp->val);
q.pop();
}
r.push_back(tmp);
}
return r;
}
int main()
{
TreeNode *root = new TreeNode(NULL);
levelOrder(root);
return 0;
}