// language C with STL(C++)
// 剑指32-III
// https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof/
/**
* 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) {
vector<vector<int>> ans;
if(root == NULL)
return ans; //空树
queue<TreeNode*> p;
queue<TreeNode*> q;
queue<int> mid;
TreeNode* temp;
q.push(root);
int level =0;
while(!empty(q)){
level++;
p.swap(q);
vector<int> linshi;
while(!empty(p)){
temp = p.front();
p.pop();
if(temp->left !=NULL)
q.push(temp->left);
if(temp->right !=NULL)
q.push(temp->right);
linshi.push_back(temp->val);
}
if(level%2 ==0){
while(!empty(linshi)){
mid.push(linshi.back());
linshi.pop_back();
}
while(!empty(mid)){
linshi.push_back(mid.front());
mid.pop();
}
}
ans.push_back(linshi);
}
return ans;
}
};
原文:https://www.cnblogs.com/gallien/p/14369730.html