题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
#include <iostream>
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
stack<TreeNode*> st;//从左往右,显示,将下一层,从左往右顺序压入栈st1中,准备从右向左出栈
stack<TreeNode*> st1;//从右往左显示,将下一层按从右向左顺序,压入栈st,准备从左向右出栈
if(pRoot != NULL) st.push(pRoot); //将根结点,压入st中
vector<vector<int>> result;//创建返回二级向量
int count = 0;//记录顺序
while(!st.empty() || !st1.empty()){
vector<int> vec;
int size = st.size(); // 读取从左往右的栈内元素个数,挨个出栈
int size1 = st1.size();//读取从右向左的栈内元素个数,挨个出栈
count++;
if(count % 2 == 1){
for(int i = 0; i < size; i++){
TreeNode* node = st.top();
st.pop();
vec.push_back(node->val);
if(node->left) st1.push(node->left);
if(node->right) st1.push(node->right);
}
}
else if(count % 2 == 0)
{
for(int i = 0; i < size1; i++){
TreeNode* node = st1.top();
st1.pop();
vec.push_back(node->val);
if(node->right) st.push(node->right);
if(node->left) st.push(node->left);
}
}
result.push_back(vec);//压入向量
}
return result;
}
};