题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
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) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pRoot TreeNode类
* @return int整型vector<vector<>>
*/
vector<vector<int> > Print(TreeNode* pRoot) {
// write code here
vector<vector<int>> res;
if (pRoot == nullptr) return res;
queue<TreeNode*> q;
queue<TreeNode*> p;
q.push(pRoot);
bool falg=true;
while (!q.empty()) {
vector<int> cur1;
int n = q.size();
falg=!falg;//奇数行翻转,偶数行不翻转
for (int i = 0; i < n; i++) {//为奇数行时
TreeNode* now1 = q.front();
q.pop();
cur1.push_back(now1->val);
if (now1->left)
q.push(now1->left);
if (now1->right)
q.push(now1->right);
}
if(falg)//为偶数行时,翻转
reverse(cur1.begin(),cur1.end());
res.push_back(cur1);
}
return res;
}
};
