题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
#include <queue>
#include <vector>
#include<algorithm>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pRoot TreeNode类
* @return int整型vector<vector<>>
*/
vector<vector<int> > Print(TreeNode* pRoot) {
// write code here
queue<TreeNode*> q;
vector<vector<int>> re;
if (pRoot) {
q.push(pRoot);
}
int j=1; //标志位,奇数层不变,偶数层反转
while (!q.empty()) {
int i=q.size();
vector<int> num;
while(i--){
TreeNode* temp=q.front();
num.push_back(temp->val);
q.pop();
if (temp->left) {
q.push(temp->left);
}
if (temp->right) {
q.push(temp->right);
}
}
if (j%2==0) {
reverse(num.begin(),num.end());
}
re.push_back(num);
j++;
}
return re;
}
};
OPPO公司福利 1182人发布
