题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
思路还是层次遍历:
对于之字形,我用的是栈来处理,栈用来反向输出。当然还可以用reverse函数。
代码:
class Solution { public: vector<vector<int> > Print(TreeNode* pRoot) { int num = 1; vector<vector<int>> ret; queue<TreeNode*> q; stack<TreeNode*> st; if(!pRoot) return ret; q.push(pRoot); while(!q.empty() || !st.empty()){ int sq = q.size(); int ss = st.size(); vector<int> ans; if(num%2 == 1){ while(sq--){ TreeNode* node = q.front(); q.pop(); ans.push_back(node->val); if(node->left) st.push(node->left); if(node->right) st.push(node->right); if(node->left) q.push(node->left); if(node->right) q.push(node->right); } ret.push_back(ans); } else{ while(ss--){ TreeNode* node = st.top(); st.pop(); ans.push_back(node->val); TreeNode* node1 = q.front(); q.pop(); if(node1->left) q.push(node1->left); if(node1->right) q.push(node1->right); } ret.push_back(ans); } num++; } return ret; } };