题解 | #把二叉树打印成多行#
把二叉树打印成多行
https://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ #include <vector> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pRoot TreeNode类 * @return int整型vector<vector<>> */ vector<vector<int>> res; // 层序遍历 vector<vector<int> > Print(TreeNode* pRoot) { // write code here if(!pRoot) return res; queue<TreeNode*> q; q.push(pRoot); vector<int> v; while (!q.empty()) { int num = q.size(); for(int i = 0; i < num; ++i) { TreeNode* tmp = q.front(); q.pop(); v.push_back(tmp->val); if(tmp->left) q.push(tmp->left); if(tmp->right) q.push(tmp->right); } res.push_back(v); v.clear(); } return res; } };
挤挤刷刷! 文章被收录于专栏
记录coding过程