时间限制:1秒 空间限制:32768K 热度指数:246831
题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
这题想了好久啊,第一感觉就是用队列+栈。
deep为奇数时,队首元素出队,按左节点、右节点存入栈;
deep为偶数时,栈顶元素出栈,按左节点、右节点存入队列。
但是,这样是行不通的。比如:【1】,【2,3】,【4,5,6,7】,按我的思路打印出来会是【1】,【3,2】,【6,7,4,5】。因为出栈操作是从右往左的,比如deep=2时,出栈顺序是3,2,而入队时,会先把3的左右子树(6,7)入队。
正确的解法应该是使用双栈。
deep为奇数时,栈1的栈顶元素出栈,按左子树、右子树存入栈2;
deep为偶数时,栈2的栈顶元素出栈,按右子树、左子树存入栈1。
/*
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 == NULL) return res;
stack<TreeNode*> sta1;
stack<TreeNode*> sta2;
sta1.push(pRoot);
vector<int> ans;
while(!sta1.empty()||!sta2.empty()){
while(!sta1.empty()){
TreeNode *temp = sta1.top();
ans.push_back(temp->val);
sta1.pop();
if(temp->left!=NULL){
sta2.push(temp->left);
}
if(temp->right!=NULL){
sta2.push(temp->right);
}
}
if(ans.size()){
res.push_back(ans);
ans.clear();
}
while(!sta2.empty()){
TreeNode *temp = sta2.top();
ans.push_back(temp->val);
sta2.pop();
if(temp->right!=NULL){
sta1.push(temp->right);
}
if(temp->left!=NULL){
sta1.push(temp->left);
}
}
if(ans.size()){
res.push_back(ans);
ans.clear();
}
}
return res;
}
};