题解 | #把二叉树打印成多行#
把二叉树打印成多行
http://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288
1
一轮AC
- 还是典型的bfs模板
- 末尾总结下当前遇到的bfs 层次题目
2 code
/*
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) {
//分行的bfs
vector<vector<int> > outV;
if(!pRoot){
return outV;
}
queue<TreeNode *> q;
q.push(pRoot);
int sz =0;
while( !q.empty()){
sz = q.size();
//inside;
vector<int> innerV;
//level control while(sz)
while(sz--){
//get queue top
TreeNode * top = q.front();
innerV.push_back(top->val);
q.pop();
//get child pushed
if(top->left){
q.push(top->left);
}
if(top->right){
q.push(top->right);
}
}
outV.push_back(innerV);
}
return outV;
}
};
3 类似题目
JZ32 从上往下打印二叉树
JZ78 把二叉树打印成多行