/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
#include <algorithm>
#include <queue>
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
queue<TreeNode *> q;
vector<vector<int> > res;
if (pRoot) {
q.push(pRoot);
}
int idx = 0;
while (!q.empty()) {
int n = q.size();
vector<int> tmp;
for (int i = 0; i < n; ++i) {
auto now = q.front();
q.pop();
tmp.push_back(now->val);
if (now->left) {
q.push(now->left);
}
if (now->right) {
q.push(now->right);
}
}
if (idx % 2) {
reverse(tmp.begin(), tmp.end());
}
res.push_back(tmp);
++idx;
}
return res;
}
};
思路:层序遍历
* 层序遍历模板
* 因为要之字形遍历,所以增加一个计数表示当前层数,从0开始
* 当前层数为奇数时,将当前层的遍历反向

京公网安备 11010502036488号