题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
/*
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 != NULL) {
vector<int> tmp;
stack<TreeNode*> st;
stack<TreeNode*> stmp;
st.push(pRoot);
TreeNode* cur;
int tag = 0;
while (!st.empty()) {
while (!st.empty()) {
cur = st.top();
st.pop();
tmp.push_back(cur->val);
if (tag == 0) {//从右往左
if (cur->left != NULL) {
stmp.push(cur->left);
}
if (cur->right != NULL) {
stmp.push(cur->right);
}
} else {//从左往右
if (cur->right != NULL) {
stmp.push(cur->right);
}
if (cur->left != NULL) {
stmp.push(cur->left);
}
}
}
tag = 1 - tag;
ans.push_back(tmp);
tmp.clear();
swap(st, stmp);
}
}
return ans;
}
};