题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
方法一:
使用两个栈来实现
一个栈存奇数层的节点,另一个栈村偶数层的节点;
/*
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*> s1;
stack<TreeNode*> s2;
s1.push(pRoot);
int layer = 1;
while (!s1.empty() || !s2.empty()) {
TreeNode* current;
vector<int> tmp;
if (layer % 2 == 1) {
while (!s1.empty()) {
current = s1.top();
s1.pop();
tmp.push_back(current->val);
if (current->left)
s2.push(current->left);
if (current->right)
s2.push(current->right);
}
} else {
while (!s2.empty()) {
current = s2.top();
s2.pop();
tmp.push_back(current->val);
if (current->right)
s1.push(current->right);
if (current->left)
s1.push(current->left);
}
}
if (tmp.size() != 0){
res.push_back(tmp);
tmp.clear();
layer++;
}
}
return res;
}
};
方法二:
使用双端队列实现
注意:奇数层时队中元素从队列头部出队,元素的孩子从队列尾部入队;偶数层时队中元素从队列尾部出队,元素的孩子从队列头部入队;
/*
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;
deque<TreeNode*> assistant;
assistant.push_back(pRoot);
int layer = 1;
int layerSize = 1;
while (!assistant.empty()) {
vector<int> tmp;
TreeNode* current;
for (int i = 0; i < layerSize; i++) {
if (layer % 2 == 1) {
current = assistant.front();
assistant.pop_front();
tmp.push_back(current->val);
if (current->left)
assistant.push_back(current->left);
if (current->right)
assistant.push_back(current->right);
} else {
current = assistant.back();
assistant.pop_back();
tmp.push_back(current->val);
if (current->right)
assistant.push_front(current->right);
if (current->left)
assistant.push_front(current->left);
}
}
layerSize = assistant.size();
layer++;
res.push_back(tmp);
}
return res;
}
};