在经典的层序遍历的基础上,对层进行就判断,偶数层就进行翻转;奇数层则保持不变。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int> > ans;
if (!pRoot) return ans; // 空指针,直接返回
queue<TreeNode*> que;
que.push(pRoot);
int c = 0; // 记录奇偶层
while(!que.empty()) { // 队列不为空
int n = que.size();
vector<int> tmp;
while (n--) { // 当前层遍历
tmp.push_back(que.front()->val);
if (que.front()->left) que.push(que.front()->left);
if (que.front()->right) que.push(que.front()->right);
que.pop();
}
c++;
if (c%2 == 0) {
reverse(tmp.begin(), tmp.end()); // 偶数层,则反转
}
ans.emplace_back(tmp);
}
return ans;
}
};


京公网安备 11010502036488号