层次遍历,借助辅助栈
奇数层的直接加入vector
偶数层加入stack,然后再弹栈到vector中
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;
bool flag=true;
if(pRoot==NULL) return res;
queue<TreeNode*> q;
q.push(pRoot);
while(!q.empty()){
int size=q.size();
vector<int> ve;
stack<int> st;
while(size--){
TreeNode* node=q.front();
q.pop();
if(flag) ve.push_back(node->val);
else st.push(node->val);
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
}
if(!flag){
while(!st.empty()){
ve.push_back(st.top());
st.pop();
}
}
if(ve.size()>0) res.push_back(ve);
flag=!flag;
}
return res;
}
};