题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
AC代码
/*
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> > vec;
if (pRoot == NULL) {
return vec;
}
stack<TreeNode*> s1, s2;
s1.push(pRoot);
while (!s1.empty() || !s2.empty()) {
vector<int> vec1;
TreeNode *cur;
while (!s1.empty()) {
cur = s1.top();
vec1.push_back(cur->val);
if (cur->left) {
s2.push(cur->left);
}
if (cur->right) {
s2.push(cur->right);
}
s1.pop();
}
if (!vec1.empty()) {
vec.push_back(vec1);
}
vector<int> vec2;
while (!s2.empty()) {
cur = s2.top();
vec2.push_back(cur->val);
if (cur->right) {
s1.push(cur->right);
}
if (cur->left) {
s1.push(cur->left);
}
s2.pop();
}
if (!vec2.empty()) {
vec.push_back(vec2);
}
}
return vec;
}
};
思路
使用双栈的结构.左右横跳(先进后出)符合之字形,使用两个栈解决存放问题.
或者一个队列,设一个奇偶flag,一下子是按left right进子节点,一下子按right left进子节点并记录size 然后每行pop就行(感觉有点麻烦)
网友评论