/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pRoot TreeNode类 * @return int整型vector<vector<>> */ vector<vector<int> > Print(TreeNode* pRoot) { // write code here vector<vector<int>>res; if (!pRoot) { return res;//如果pRoot为空,直接返回res } queue<TreeNode*>q; TreeNode* cur; q.push(pRoot);//将头指针装入队列 bool flag=true;//定义一个bool值 while (!q.empty()) { vector<int>v; int n = q.size();//定义q的大小 flag=!flag;//奇数行不反转 for (int j = 0; j < n; j++) { cur = q.front(); q.pop(); v.push_back(cur->val); if (cur->left) { q.push(cur->left); } if (cur->right) { q.push(cur->right); } } if(flag){ reverse(v.begin(),v.end()); }//偶数行反转 res.push_back(v);//传入vector } return res; } };