题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
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) { } }; */ class Solution { public: vector<vector<int> > Print(TreeNode* pRoot) { vector<vector<int>>res; if(pRoot==NULL) { return res;//空的就直接返回一个空的 } int n ; queue<TreeNode*>q; q.push(pRoot); //类似于二叉树的层序遍历,只不过需要最后需要反转 bool flag = true; while(!q.empty()) { vector<int>row; n = q.size(); flag = !flag; for(int i = 0;i<n;i++) { TreeNode*tmp; tmp = q.front(); row.push_back(q.front()->val); q.pop(); if(tmp->left!=NULL) { q.push(tmp->left); } if(tmp->right!=NULL) { q.push(tmp->right); } } if(flag) reverse(row.begin(),row.end()); res.push_back(row); } return res; } };