按照上一题使用的层序遍历,只是奇数层和偶数层向level中放入的顺序不一样
-
奇数层 从左到右
-
偶数层 从右到左
其他完全一样
class Solution {
public:
vector<vector<int>> printFromTopToBottom(TreeNode* root) {
if(!root) return {};
vector<vector<int>> res;
queue<TreeNode*> q;
q.push(root);
bool from_left_to_right = true;
while(q.size())
{
int n = q.size();
vector<int> level(n);
for(int i = 0; i < n; ++i)
{
auto node = q.front();
q.pop();
level[from_left_to_right ? i : n-1-i] = node->val; // 放入顺序不一样
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
}
res.push_back(level);
from_left_to_right = !from_left_to_right;
}
return res;
}
};