1、辅助队列
题目要求等价于实现层序遍历,区别在于我们在不同层时需要从左到右和从右到左进行遍历。为了区分不同的层,我们可以使用isLtoR来判断应该采取何种方式进行遍历。若需要则可以在最后对存放当前层的数组进行逆序。
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode *root) {
vector<vector<int>> res;
if (!root) return res;
queue<TreeNode *> dq;
bool isLtoR = false;
dq.push(root);
while (!dq.empty()) {
int size = dq.size();
vector<int> temp_res;
for (int i = 0; i < size; ++i) {
TreeNode *cur = dq.front();
dq.pop();
temp_res.emplace_back(cur->val);
if (cur->left) dq.push(cur->left);
if (cur->right) dq.push(cur->right);
}
if (isLtoR) reverse(temp_res.begin(), temp_res.end());
isLtoR = !isLtoR;
res.emplace_back(temp_res);
}
return res;
}
};