Idea: This
question is a bfs template question, by using a linked list (I use deque myself, but I don't use it) to record the nodes of a certain layer that I have traversed, and the rest is a very typical bfs routine.
Code:
/**
* 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) {
deque<TreeNode*> q;
vector<vector<int> > st;
if(root==NULL) return st;
q.push_back(root);
while(!q.empty()){
vector<int> p;
int len = q.size();
for(int i=1;i<=len;++i){
TreeNode* k = q.front();
q.pop_front();
p.push_back(k->val);
if(k->left) q.push_back(k->left);
if(k->right) q.push_back(k->right);
}
st.push_back(p);
}
return st;
}
};