题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
#include <vector>
#include <stack>
/*
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> > res;
if (!pRoot) {
return res;
}
stack<TreeNode*> m_stack[2];
int curdigit = 0;//代表奇偶层。0:奇数层 1:偶数层
int lastdigit = 1;//记录上一次是哪一层
m_stack[0].push(pRoot);
while (!m_stack[0].empty() || !m_stack[1].empty()) {
if (lastdigit == 1) {
curdigit = 0;
} else {
curdigit = 1;
}
int row = m_stack[curdigit].size();
vector<int> m_vec;
while (row--) {
TreeNode* node = m_stack[curdigit].top();
m_stack[curdigit].pop();
m_vec.push_back(node->val);
if (curdigit % 2 == 0) {
if (node->left) m_stack[1].push(node->left);
if (node->right) m_stack[1].push(node->right);
} else {
if (node->right) m_stack[0].push(node->right);
if (node->left) m_stack[0].push(node->left);
}
}
lastdigit = curdigit;
res.push_back(m_vec);
}
return res;
}
};
#如何看待2023届秋招##我的求职思考##你的秋招进展怎么样了#
查看1道真题和解析