/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
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 == nullptr) return res;
TreeNode* cur = root;
TreeNode* curEnd = root; //当前层的最后一个节点
TreeNode* nextEnd = nullptr; //标记下一层节点的最右节点
queue<TreeNode*> q;
q.push(root);
vector<int> levelRes; //标记每一层的节点
while(q.size()){
cur = q.front();
q.pop();
if(cur->left){
q.push(cur->left);
nextEnd = cur->left;
}
if(cur->right){
q.push(cur->right);
nextEnd = cur->right;
}
if(cur == curEnd){ //到了当前层的最右节点,则结算,把结果添加入res,并刷新curEnd和nextEnd
levelRes.push_back(cur->val);
res.push_back(levelRes);
levelRes.clear();
curEnd = nextEnd;
nextEnd = nullptr;
}else{
levelRes.push_back(cur->val); //记录当前层节点
}
}
return res;
}
};