题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } }; */ #include <cstddef> class Solution { public: vector<vector<int> > Print(TreeNode* pRoot) { vector<vector<int>> res; queue<TreeNode *> q; if(!pRoot) return res; int count = 0; q.push(pRoot); while(!q.empty()){ vector<int> ans; count ++; int size = q.size(); for(int i = 0;i < size;i ++){ cout << i << " "; if(q.front() -> left) q.push(q.front()->left); if(q.front() -> right) q.push(q.front()->right); if(count % 2 == 1){ ans.push_back(q.front() -> val); } else if(count % 2 == 0){ ans.insert(ans.begin(),q.front() -> val); } q.pop(); } res.push_back(ans); } return res; } };
重写这道题,发现把q.size()写到for里面去了,for里面又在操作q,导致出错。