题解 | #把二叉树打印成多行#
把二叉树打印成多行
http://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int>> res;
vector<int> ans;
if(!pRoot)
return res;
queue<TreeNode*> q;
q.push(pRoot);
ans.push_back(pRoot->val);
res.push_back(ans); // ans记录下一层的元素
while(!q.empty()) {
int n = ans.size();
ans.clear(); // 将ans中当前层的元素清空
while(n--) { // 遍历q中当前层的元素
auto t = q.front();
q.pop();
if(t->left) {
q.push(t->left);
ans.push_back(t->left->val);
}
if(t->right) {
q.push(t->right);
ans.push_back(t->right->val);
}
}
if(ans.size()) // 如果下一层中有元素
res.push_back(ans);
}
return res;
}
};