二叉树的层序遍历,特判版。
特判还是比较难的,主要是需要用到tmp.insert(tmp.begin(), x->val);实现从右到左打印
class Solution {
public:
vector > Print(TreeNode* pRoot) {
if (pRoot == nullptr) return {};
vector<vector<int>> res;
queue<TreeNode*> Q;
Q.push(pRoot);
int odd = 0;
vector<int> tmp;
while (!Q.empty()) {
tmp.clear();
int len = Q.size();
for(int i = 0; i < len; ++i){
TreeNode* x = Q.front();
Q.pop();
if(x == nullptr) continue;
Q.push(x->left);
Q.push(x->right);
// 保持左右孩子入队不变,打印的时候需要特判
if(odd % 2 == 0){
// 第一行 从左到右打印
tmp.push_back(x->val);
}else{
// 这样可以实现从右向左打印
tmp.insert(tmp.begin(), x->val);
}
}
odd++;
if(!tmp.empty()) res.push_back(tmp);
}
return res;
}
};