题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ #include <algorithm> #include <queue> #include <vector> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pRoot TreeNode类 * @return int整型vector<vector<>> */ vector<vector<int>> visit_seq(TreeNode* root) { vector<TreeNode*> v; v.push_back(nullptr); v.push_back(root); queue<TreeNode*> q; q.push(root); while (!q.empty()) { // 层序遍历,把节点都装进容器里面,而且每层使用空节点间开 v.push_back(nullptr); // std::cout << " v size = " << v.size() << std::endl; int n = q.size(); // std::cout << " n = " << n << std::endl; for(int i = 0; i < n; ++i) { TreeNode* tmp = q.front(); q.pop(); if(tmp->left){ v.push_back(tmp->left); // std::cout << tmp->left->val << " "; q.push(tmp->left); } if(tmp->right){ v.push_back(tmp->right); // std::cout << tmp->right->val << " "; q.push(tmp->right); } } // std::cout << std::endl<< " *********** " << std::endl; } v.pop_back(); // std::cout << v.size() << std::endl; vector<int> res_1; // 存储同一层的节点的val值 vector<vector<int>> res; int n = v.size(); bool flag = true; // 从左到右 for(int i = 0; i < n; ++i) { if (v[i]) { // 表示同一层节点 res_1.push_back(v[i]->val); } if(!v[i] && !res_1.empty()) // 表示到达下一层节点,将上一层节点的val存入容器中,使用flag来记录遍历顺序 { // std::cout << std::endl << " *** " << std::endl; flag = !flag; if(flag) reverse(res_1.begin(), res_1.end()); // res.push_back(res_1); res_1.clear(); } if(i == n-1) { flag = !flag; if(flag) reverse(res_1.begin(), res_1.end()); res.push_back(res_1); res_1.clear(); } } return res; } vector<vector<int>> Print(TreeNode* pRoot) { // write code here TreeNode* root = pRoot; if(!root) return {}; return visit_seq(root); } };
挤挤刷刷! 文章被收录于专栏
记录coding过程