题解 | #从上往下打印二叉树#
从上往下打印二叉树
http://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701
感想
一轮AC
- 代码虽小 五脏俱全
- bfs最小模板的认识
- queue的掌握认识
- 各种层次遍历的基础
code
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
vector<int> vec;
//bfs mode
if(!root){
return vec;
}
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
TreeNode* top = q.front();
vec.push_back(top->val);
q.pop();
//no level control ,while(sz)
if(top->left){
q.push(top->left);
}
if(top->right){
q.push(top->right);
}
}
return vec;
}
};