题解 | #把二叉树打印成多行# | C++
把二叉树打印成多行
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 <queue>
#include <vector>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pRoot TreeNode类
* @return int整型vector<vector<>>
*/
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int>> ans;
if (pRoot == nullptr) return ans;
std::queue<TreeNode*> q;
q.push(pRoot);
while (!q.empty()) {
int n = q.size();
vector<int> item;
while (n-- >= 1) {
auto front = q.front();
q.pop();
item.push_back(front->val);
if (front->left) {
q.push(front->left);
}
if (front->right) {
q.push(front->right);
}
}
ans.push_back(std::move(item));
}
return ans;
}
};

