基本数据结构操作,二叉树的层次遍历。
代码:
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
vector<vector<int> > res;
vector<TreeNode *> layer;
bool l2r = true; layer.push_back(root);
while (!layer.empty()) {
vector<TreeNode *> nextLayer;
vector<int> path;
for (auto node : layer) {
if (!node)
continue;
path.push_back(node->val);
nextLayer.push_back(node->left);
nextLayer.push_back(node->right);
}
if (!l2r) {
for (int i = ; (i << ) < path.size(); i++)
swap(path[i], path[path.size() - i - ]);
}
if (!path.empty())
res.push_back(path);
layer = nextLayer;
l2r = !l2r;
} return res;
}