题解 | #把二叉树打印成多行# 经典层序遍历
把二叉树打印成多行
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 <unistd.h> #include <vector> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pRoot TreeNode类 * @return int整型vector<vector<>> */ vector<vector<int> > Print(TreeNode* pRoot) { // write code here // 首先想到层序遍历 queue<TreeNode*> que; vector<vector<int>> res; if(pRoot == nullptr) return res; que.push(pRoot); while(!que.empty()){ int n = que.size(); vector<int> path; for(int i=0; i<n ;i++){ TreeNode *node = que.front(); que.pop(); if(node -> left) que.push(node->left); if(node -> right) que.push(node->right); path.push_back(node->val); } res.push_back(path); } return res; } };